您现在的位置是:网站首页> 编程资料编程资料
.NET Core利用BsonDocumentProjectionDefinition和Lookup进行 join 关联查询(推荐)_实用技巧_
2023-05-24
318人已围观
简介 .NET Core利用BsonDocumentProjectionDefinition和Lookup进行 join 关联查询(推荐)_实用技巧_
前序
前段时间由于项目需要用到MongoDB,但是MongoDB不建议Collection join 查询,网上很多例子查询都是基于linq 进行关联查询。但是在stackoverflow找到一个例子,程序员的朋友们请善于利用google搜索。主要介绍一个查询角色的所有用户的例子。MongoDB创建Collection 和准备数据,请自行处理。
1. 准备实体模型
////// 用户实体(Collection) /// 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; } } ////// 角色实体(Collection) /// public class Role { public Guid RoleId { get; set; } public string RoleName { get; set; } public DateTime CreateTime { get; set; } } ////// 构建用户Dto(不在Mongo创建Collection) /// 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
BsonDocumentProjectionDefinitionprojectionDefinition = new BsonDocumentProjectionDefinition ( 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; Listlist = database.GetCollection (typeof(User).Name) .Aggregate() //过滤条件 .Match(Builders .Filter.Eq("IsDelete", false)) .Match(Builders .Filter.Eq("RoleId", roleId)) //连接Role .Lookup(typeof(Role).Name, "RoleId", "RoleId", typeof(UserDto).Name) //查询需要显示的列 .Project(projectionDefinition) .As ().ToList();
到此这篇关于.NET Core利用BsonDocumentProjectionDefinition和Lookup进行 join 关联查询的文章就介绍到这了,更多相关.net core join 关联查询内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
您可能感兴趣的文章:
相关内容
- 使用Hangfire+.NET 6实现定时任务管理(推荐)_实用技巧_
- .Net core Blazor+自定义日志提供器实现实时日志查看器的原理解析_实用技巧_
- .Net Core和RabbitMQ限制循环消费的方法_实用技巧_
- .NET API 接口数据传输加密最佳实践记录_实用技巧_
- .NET6打包部署到Windows Service的全过程_实用技巧_
- Entity Framework使用DBContext实现增删改查_实用技巧_
- .NET Core部署为Windows服务的详细步骤_实用技巧_
- ASP.NET MVC实现本地化和全球化_实用技巧_
- AspNetCore&MassTransit Courier实现分布式事务的详细过程_实用技巧_
- .NET中的MassTransit分布式应用框架详解_实用技巧_
