前序
前段时间由于项目需要用到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 关联查询内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论