在C#中执行查找聚合后,我在过滤mongodb中的文档时遇到了这个问题。我正在使用多个查询,因此需要从上一个子集合中过滤掉文档。以下是收藏列表:
集合1: ID,ParentId,Desc,索引
集合2 ID,ParentId,Desc,索引,Coll2Desc1,Coll2Desc2
集合3 ID,ParentId,Desc,索引,Coll3Desc1,Coll3Desc2
集合4 ID,ParentId,Desc,索引,Coll4Desc1,Coll4Desc2
现在,我需要过滤并仅获取Coll4Desc1不为null或为空的那些记录。我尝试在投影代码后添加$ match,但不起作用。如果有人可以帮助我过滤掉所需的文档,那将非常好。
以下是我编写的查找聚合代码:
var collectionList = list.OrderBy(x => x.CollectionOrder).Select(x => x.CollectionName).Distinct().ToList();
// Load data into deviations
var listOfDocuments = new List<BsonDocument>();
var firstCollection = dbContext.GetCollection(collectionList[0]);
var options = new AggregateOptions()
{
AllowDiskUse = false
};
var previousCollectionName = "";
var sortProject = new BsonDocument();
var groupBy = new List<BsonDocument>();
for (int i = 0; i < collectionList.Count - 1; i++)
{
var collectionName = collectionList[i];
IMongoCollection<BsonDocument> collection = dbContext.GetCollection(collectionName);
if (i == 0)
{
firstCollection = collection;
var firstarray = new BsonDocument("$project", new BsonDocument()
.Add("_id", 0)
.Add(collectionName, "$$ROOT"));
listOfDocuments.Add(firstarray);
}
else
{
// join all the collections
var remainingArray = new BsonDocument("$lookup", new BsonDocument()
.Add("localField", previousCollectionName + "." + "Id")
.Add("from", collectionName)
.Add("foreignField", "ParentId")
.Add("as", collectionName));
listOfDocuments.Add(remainingArray);
remainingArray = new BsonDocument("$unwind", new BsonDocument()
.Add("path", "$" + collectionName)
.Add("preserveNullAndEmptyArrays", new BsonBoolean(true)));
listOfDocuments.Add(remainingArray);
sortProject.Add(previousCollectionName + "." + "Id", 1);
}
previousCollectionName = collectionName;
}
// Project the columns
var columnList = list.OrderBy(x => x.ColumnOrder).Where(x => x.IsVisible == true).ToList();
var docProjection = new BsonDocument();
for (int i = 0; i < columnList.Count; i++)
{
docProjection.Add(columnList[i].ColumnName, "$" + columnList[i].CollectionName + "." + columnList[i].FieldName);
}
listOfDocuments.Add(new BsonDocument("$project", docProjection));
listOfDocuments.Add(new BsonDocument("$sort", sortProject));
var match2 = new BsonDocument
{
{
"$match",
new BsonDocument
{
{"Collection4.Coll4Desc1", new BsonDocument
{
{
"$ne", ""
}
}
}
}
}
};
listOfDocuments.Add(match2);
PipelineDefinition<BsonDocument, BsonDocument> pipeline = listOfDocuments;
var listOfDocs = new List<BsonDocument>();
firstCollection.AggregateAsync(pipeline, options))
using (var cursor = firstCollection.Aggregate(pipeline, options))
{
while (cursor.MoveNext())
{
var batch = cursor.Current;
foreach (BsonDocument document in batch)
{
listOfDocs.Add(document);
}
}
}