【发布时间】:2026-01-31 17:00:02
【问题描述】:
我希望能够先进行联合,然后再进行交集。
我的文档结构:
{
"_id" : 1,
"items" : [
52711,
201610,
273342,
279449,
511250
]
},
{
"_id" : 2,
"items" : [
246421,
390200
]
}
此集合包含数千个上述形式的文档。 我想对一组文档执行联合,然后对从联合返回的集合执行交集。
例如:
Set 1 contains Id: [1,2,3,4,5]
Set 2 Contains Id: [3,4,5,6,7,8]
Set 3 Contains Id: [12,14,15,16,17]
它应该联合集合1和集合2和集合3中的所有列表项。然后对每个集合的结果进行交集。
到目前为止,我得到了如下的列表联合查询:
db.getCollection('Test').aggregate([
{ "$match": { "_id": { "$in": [1, 2, 3] } } },
{
"$group": {
"_id": 0,
"data": { "$push": "$items" }
}
},
{
"$project": {
"items": {
"$reduce": {
"input": "$data",
"initialValue": [],
"in": { "$setUnion": ["$$value", "$$this"] }
}
}
}
}
])
我现在也在 c# 中做这一切:
var group = new BsonDocument
{
{ "_id", 0 },
{
"data", new BsonDocument {{"$push", "$items" } }
}
};
var project = new BsonDocument
{
{"items", new BsonDocument
{
{ "$reduce", new BsonDocument
{
{ "input", "$data"},
{ "initialValue", new BsonArray()},
{ "in", new BsonDocument { {"$setUnion", new BsonArray { "$$value", "$$this" }}}}
}
}
}
}
};
var result = qaCollection.Aggregate()
.Match(Builders<QAList>.Filter.In(x => x.Id, list))
.Group(group)
.Project(project)
.FirstOrDefault();
此查询需要一些时间,因为它可能会返回大量数据。因此,如果我可以传递多个集合,它会合并单独的集合并将它们相交,这样数据就不会太大而无法返回。
提前谢谢..
【问题讨论】:
标签: c# mongodb mongodb-query aggregation-framework mongodb-.net-driver