.net core-利用BsonDocumentProjectionDefinition和Lookup进行 join 关联查

[复制链接]
发表于 2022-10-22 21:13:10 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
前序

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

 
  1.     /// <summary>
  2.     /// 用户实体(Collection)
  3.     /// </summary>
  4.     public class User
  5.     {
  6.         public Guid UserId { get; set; }
  7.         public string UserName { get; set; }
  8.         public string Password { get; set; }
  9.         public bool IsDelete { get; set; }
  10.         public DateTime CreateTime { get; set; }
  11.         public Guid RoleId { get; set; }
  12.     }
  13.     /// <summary>
  14.     /// 角色实体(Collection)
  15.     /// </summary>
  16.     public class Role
  17.     {
  18.         public Guid RoleId { get; set; }
  19.         public string RoleName { get; set; }
  20.         public DateTime CreateTime { get; set; }
  21.     }
  22.     /// <summary>
  23.     /// 构建用户Dto(不在Mongo创建Collection)
  24.     /// </summary>
  25.     public class UserDto
  26.     {
  27.         public Guid UserId { get; set; }
  28.         public string UserName { get; set; }
  29.         public DateTime CreateTime { get; set; }
  30.         public Guid RoleId { get; set; }
  31.         public string RoleName { get; set; }
  32.     }
复制代码
 
2 .前置连接Mongo代码
  1.            var client = new MongoClient("xxx");
  2.            var database = client.GetDatabase("xxx");
复制代码
3. 构建BsonDocumentProjectionDefinition
  1. BsonDocumentProjectionDefinition<BsonDocument> projectionDefinition = new BsonDocumentProjectionDefinition<BsonDocument>(
  2.                         new BsonDocument("UserId", "$UserId")
  3.                        .Add("UserName", "$UserName")
  4.                        .Add("CreateTime", "$CreateTime")
  5.                        .Add("RoleId", "$RoleId")
  6.                        .Add("RoleName", new BsonDocument("$arrayElemAt", new BsonArray().Add("$Role.RoleName").Add(0)))
  7.                     );
复制代码
4.利用 Lookup 进行关联
  1.             Guid roleId = Guid.Empty;
  2.             List<UserDto> list = database.GetCollection<BsonDocument>(typeof(User).Name)
  3.                 .Aggregate()
  4.                 //过滤条件
  5.                 .Match(Builders<BsonDocument>.Filter.Eq("IsDelete", false))
  6.                 .Match(Builders<BsonDocument>.Filter.Eq("RoleId", roleId))
  7.                 //连接Role
  8.                 .Lookup(typeof(Role).Name, "RoleId", "RoleId", typeof(UserDto).Name)
  9.                 //查询需要显示的列
  10.                 .Project(projectionDefinition)
  11.                 .As<UserDto>().ToList();
复制代码
第一次写博客,各位大佬请指教。
 
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表