.NET?Core利用BsonDocumentProjectionDefinition和Lookup進(jìn)行?join?關(guān)聯(lián)查詢(推薦)
前序
前段時(shí)間由于項(xiàng)目需要用到MongoDB,但是MongoDB不建議Collection join 查詢,網(wǎng)上很多例子查詢都是基于linq 進(jìn)行關(guān)聯(lián)查詢。但是在stackoverflow找到一個(gè)例子,程序員的朋友們請(qǐng)善于利用google搜索。主要介紹一個(gè)查詢角色的所有用戶的例子。MongoDB創(chuàng)建Collection 和準(zhǔn)備數(shù)據(jù),請(qǐng)自行處理。
1. 準(zhǔn)備實(shí)體模型
/// <summary>
/// 用戶實(shí)體(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>
/// 角色實(shí)體(Collection)
/// </summary>
public class Role
{
public Guid RoleId { get; set; }
public string RoleName { get; set; }
public DateTime CreateTime { get; set; }
}
/// <summary>
/// 構(gòu)建用戶Dto(不在Mongo創(chuàng)建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. 構(gòu)建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 進(jìn)行關(guān)聯(lián)
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();到此這篇關(guān)于.NET Core利用BsonDocumentProjectionDefinition和Lookup進(jìn)行 join 關(guān)聯(lián)查詢的文章就介紹到這了,更多相關(guān).net core join 關(guān)聯(lián)查詢內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Asp.net mvc實(shí)時(shí)生成縮率圖到硬盤
這篇文章主要介紹了Asp.net mvc實(shí)時(shí)生成縮率圖到硬盤的相關(guān)資料,需要的朋友可以參考下2016-05-05
ASP.NET中使用AspnetAccessProvider
ASP.NET中使用AspnetAccessProvider...2007-09-09
解決 .NET Core 中 GetHostAddressesAsync 引起的 EnyimMemcached 死鎖問題
這篇文章主要介紹了解決 .NET Core 中 GetHostAddressesAsync 引起的 EnyimMemcached 死鎖問題的相關(guān)資料,需要的朋友可以參考下2016-09-09
ASP.NET MVC 3實(shí)現(xiàn)訪問統(tǒng)計(jì)系統(tǒng)
我們將介紹用ASP.NET MVC 3實(shí)現(xiàn)一個(gè)訪問統(tǒng)計(jì)系統(tǒng),包括統(tǒng)計(jì)代碼和Cookie等方面,希望對(duì)大家有所幫助。2015-10-10
ASP.NET中操作SQL數(shù)據(jù)庫(連接字符串的配置及獲取)
要想在ASP.NET中操作SQL數(shù)據(jù)庫首先需要在WebConfig中配置數(shù)據(jù)庫連接字符串,之后在.cs文件中獲取連接字符串,具體的配置及獲取方法如下,感興趣的朋友可以參考下哈2013-06-06

