当前位置: 代码网 > it编程>编程语言>Asp.net > .NET Core利用BsonDocumentProjectionDefinition和Lookup进行 join 关联查询(推荐)

.NET Core利用BsonDocumentProjectionDefinition和Lookup进行 join 关联查询(推荐)

2024年06月02日 Asp.net 我要评论
前序前段时间由于项目需要用到mongodb,但是mongodb不建议collection join 查询,网上很多例子查询都是基于linq 进行关联查询。但是在stackoverflow找到一个例子,

前序

前段时间由于项目需要用到mongodb,但是mongodb不建议collection join 查询,网上很多例子查询都是基于linq 进行关联查询。但是在stackoverflow找到一个例子,程序员的朋友们请善于利用google搜索。主要介绍一个查询角色的所有用户的例子。mongodb创建collection 和准备数据,请自行处理。

1. 准备实体模型

/// <summary>
    /// 用户实体(collection)
    /// </summary>
    public class user
    {
        public guid userid { get; set; }

        public string username { get; set; }

        public string password { get; set; }

        public bool isdelete { get; set; }

        public datetime createtime { get; set; }

        public guid roleid { get; set; }
    }
    /// <summary>
    /// 角色实体(collection)
    /// </summary>
    public class role
    {
        public guid roleid { get; set; }

        public string rolename { get; set; }

        public datetime createtime { get; set; }
    }
    /// <summary>
    /// 构建用户dto(不在mongo创建collection)
    /// </summary>
    public class userdto
    {
        public guid userid { get; set; }

        public string username { get; set; }

        public datetime createtime { get; set; }

        public guid roleid { get; set; }

        public string rolename { get; set; }
    }

2 .前置连接mongo代码

 var client = new mongoclient("xxx");
           var database = client.getdatabase("xxx");

3. 构建bsondocumentprojectiondefinition

bsondocumentprojectiondefinition<bsondocument> projectiondefinition = new bsondocumentprojectiondefinition<bsondocument>(
                        new bsondocument("userid", "$userid")
                       .add("username", "$username")
                       .add("createtime", "$createtime")
                       .add("roleid", "$roleid")
                       .add("rolename", new bsondocument("$arrayelemat", new bsonarray().add("$role.rolename").add(0)))
                    );

4.利用 lookup 进行关联

guid roleid = guid.empty;
            list<userdto> list = database.getcollection<bsondocument>(typeof(user).name)
                .aggregate()
                //过滤条件
                .match(builders<bsondocument>.filter.eq("isdelete", false))
                .match(builders<bsondocument>.filter.eq("roleid", roleid))
                //连接role
                .lookup(typeof(role).name, "roleid", "roleid", typeof(userdto).name)
                //查询需要显示的列
                .project(projectiondefinition)
                .as<userdto>().tolist();

到此这篇关于.net core利用bsondocumentprojectiondefinition和lookup进行 join 关联查询的文章就介绍到这了,更多相关.net core  join 关联查询内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com