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

2023-12-05 0 949
目录
  • 前序
  • 1. 准备实体模型
  • 2 .前置连接Mongo代码
  • 3. 构建BsonDocumentProjectionDefinition
  • 4.利用 Lookup 进行关联

前序

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

到此这篇关于.NETCore利用BsonDocumentProjectionDefinition和Lookup进行join关联查询的文章就介绍到这了,更多相关.netcorejoin关联查询内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源网!

您可能感兴趣的文章:

  • 在ASP.NET 2.0中操作数据之六十七:在TableAdapters中使用JOINs
  • vb.net操作注册表的方法分析【增加,修改,删除,查询】
  • ASP.NET MVC5 实现分页查询的示例代码
  • asp.net实现的MVC跨数据库多表联合动态条件查询功能示例

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 ASP.NET .NET Core利用BsonDocumentProjectionDefinition和Lookup进行 join 关联查询(推荐) https://www.u-9.cn/biancheng/aspnet/94452.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务