簡體   English   中英

遍歷MongoDB集合並將其加入C#

[英]Looping through MongoDB collections and joining them in C#

我在MongoDB中有一個集合,該集合包含帶有我需要工作的集合名稱的文檔。 我需要查詢此集合,從該集合內的文檔中獲取所有集合名稱,然后查詢這些集合並根據ParentId引用將它們加入。 以下是存儲其他集合名稱的集合

db.AllInfoCollection.find()
{
    "_id" : ObjectId("5b83b982a5e17c383c8424f3"),
    "CollName" : "Collection1",
},
{
    "_id" : ObjectId("5b83b9aaa5e17c383c8424f7"),
    "CollName" : "Collection2",
},
{
    "_id" : ObjectId("5b83b9afa5e17c383c8424f8"),
    "CollName" : "Collection3",
},
{
    "_id" : ObjectId("5b83b9b5a5e17c383c8424f9"),
    "CollName" : "Collection4",
},
{
    "_id" : ObjectId("5b83b9b9a5e17c383c8424fa"),
    "CollName" : "Collection5",
},
{
    "_id" : ObjectId("5b84f41bc5eb3f1f7c291f94"),
    "CollName" : "Collection6",
}

以上所有集合(Collection1,Collection2,..... Collection6)都是在運行時使用空文檔創建的。 它們通過Id和ParentId字段相互連接。 現在,我需要查詢此AllInfoCollection ,獲取集合名稱並將其加入並生成最終的加入($ lookup)輸出。 我可以查詢並獲取集合列表,但是我不確定如何在for循環內添加查找投影。 任何幫助,將不勝感激。

public void RetrieveDynamicCollection()
    {
        IMongoDatabase _db = client.GetDatabase("MyDb");
        var collectionList = _db.GetCollection<AllInfoCollection>("AllInfoCollection").AsQueryable().Distinct().Select(x => x.CollectionName).ToList();

        for(int i = 0; i < collectionList.Count; i++)
        {
            var collectionName = collectionList[i];
            IMongoCollection<BsonDocument> collection = _db.GetCollection<BsonDocument>(collectionName);
            var options = new AggregateOptions()
            {
                AllowDiskUse = false
            };
            //not able to proceed here
        }

    }

最終,我能夠使用所有必需的聯接(查找聚合)動態檢索集合,如下所示,希望它能對某人有所幫助:

public async Task<string> RetrieveDynamicCollection()
    {
        try
        {
            IMongoDatabase _db = client.GetDatabase("MyDB");
            var list = _db.GetCollection<HazopCollectionInfo>("AllCollectionInfo").AsQueryable().ToList();
            var collectionList = list.OrderBy(x => x.CollectionOrder).Select(x => x.CollectionName).Distinct().ToList();

            var listOfJoinDocuments = new List<BsonDocument>();

            var firstCollection = _db.GetCollection<BsonDocument>(collectionList[0]);
            var options = new AggregateOptions()
            {
                AllowDiskUse = false
            };
            var previousCollectionName = "";
            for (int i = 0; i < collectionList.Count; i++)
            {
                var collectionName = collectionList[i];
                IMongoCollection<BsonDocument> collection = _db.GetCollection<BsonDocument>(collectionName);
                if (i == 0)
                {
                    firstCollection = collection;
                    var firstarray = new BsonDocument("$project", new BsonDocument()
                        .Add("_id", 0)
                        .Add(collectionName, "$$ROOT"));

                    listOfJoinDocuments.Add(firstarray);
                }
                else
                {
                    var remainingArray = new BsonDocument("$lookup", new BsonDocument()
                            .Add("localField", previousCollectionName + "." + "Id")
                            .Add("from", collectionName)
                            .Add("foreignField", "ParentId")
                            .Add("as", collectionName));
                    listOfJoinDocuments.Add(remainingArray);

                    remainingArray = new BsonDocument("$unwind", new BsonDocument()
                            .Add("path", "$" + collectionName)
                            .Add("preserveNullAndEmptyArrays", new BsonBoolean(true)));
                    listOfJoinDocuments.Add(remainingArray);
                }
                previousCollectionName = collectionName;
            }
            // Project the columns 
            list.OrderBy(x => x.ColumnOrder);
            var docProjection = new BsonDocument();
            for(int i=0;i<list.Count;i++)
            {
                docProjection.Add(list[i].ColumnName, "$"+list[i].CollectionName + "." + list[i].FieldName);
            }

            listOfJoinDocuments.Add(new BsonDocument("$project", docProjection));


            PipelineDefinition<BsonDocument, BsonDocument> pipeline = listOfJoinDocuments;

            var listOfDocs = new List<BsonDocument>();
            using (var cursor = await firstCollection.AggregateAsync(pipeline, options))
            {
                while (await cursor.MoveNextAsync())
                {
                    var batch = cursor.Current;
                    foreach (BsonDocument document in batch)
                    {
                        listOfDocs.Add(document);
                    }
                }
            }

            var jsonString = listOfDocs.ToJson(new MongoDB.Bson.IO.JsonWriterSettings { OutputMode = MongoDB.Bson.IO.JsonOutputMode.Strict });

            return jsonString;
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM