遍历MongoDB集合并将其加入C#

时间:2018-08-28 18:08:22

标签: c# mongodb mongodb-query

我在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
        }

    }

1 个答案:

答案 0 :(得分:2)

最后,我能够使用所有必需的联接(查找聚合)动态地检索集合,如下所示,希望它能对某人有所帮助:

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;
        }
    }