.NET?Core利用BsonDocumentProjectionDefinition和Lookup进行?join?关联查询(推荐)
(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun)
前序
前段时间由于项目需要用到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 关联查询内容请搜索程序员之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持程序员之家!
相关文章
如何使用签名保证ASP.NET MVC OR WEBAPI的接口安全
这篇文章主要介绍了如何使用签名保证ASP.NET MVC OR WEBAPI的接口安全,帮助大家更好的理解和学习使用.net技术,感兴趣的朋友可以了解下2021-04-04.NET程序集引用COM组件MSScriptControl遇到问题的解决方法
这篇文章主要为大家详细介绍了.NET程序集引用COM组件MSScriptControl遇到问题的解决方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-01-01使用DataGrid中扩展ItemRenderer和HeaderRenderer进行操作
这两天在用Flex DataGrid做点东西,走了不少弯路,现将心得分享一下。2009-02-02
最新评论