【问题标题】:Looping through MongoDB collections and joining them in C#循环遍历 MongoDB 集合并在 C# 中加入它们
【发布时间】:2019-02-03 10:44:05
【问题描述】:

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

    }

【问题讨论】:

    标签: c# mongodb mongodb-query


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 2018-06-16
      • 2016-07-16
      • 2014-08-13
      • 1970-01-01
      相关资源
      最近更新 更多