.net core-利用BsonDocumentProjectionDefinition和Lookup进行 join 关联查询(MongoDB)

前序

     前段时间由于项目需要用到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();
复制代码

第一次写博客,各位大佬请指教。

 

posted @   Code的那些事  阅读(247)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示