日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

.NET?Core利用BsonDocumentProjectionDefinition和Lookup進行?join?關聯查詢(推薦)_實用技巧

作者:Code的那些事 ? 更新時間: 2022-12-04 編程語言

前序

前段時間由于項目需要用到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();

原文鏈接:https://www.cnblogs.com/honglinjia/p/16813761.html

欄目分類
最近更新