我有两个独立的集合,比如说 collA 和 collB。两者都有一些共同的字段,假设 fieldA、fieldB、fieldC 在两个集合中都可用。
db.getCollection('collA').aggregate([
{
"$match":{
// Some filter condition
}
},
{
"$project":{
"_id":1,
"fieldA":1,
"fieldB":1,
"fieldC":1
}
}
]);
假设我从 collA 获得 10 条记录
db.getCollection('collB').aggregate([
{
"$match":{
// Some filter condition
}
},
{
"$project":{
"_id":1,
"fieldA":1,
"fieldB":1,
"fieldC":1
}
}
]);
假设我从 collB 获得 5 条记录
现在,我想做的是合并这 15 条记录并执行其他聚合操作,如 $group 和许多其他操作。
有没有办法用 mongoDB 聚合或任何其他替代选项来做到这一点?
假设两个集合的架构如下
CollA
{
fieldA : String,
fieldB : String
fieldC : String
fieldD : String
}
CollB
{
fieldA : String,
fieldB : String
fieldC : String
fieldE : String
}
最佳答案
你可以试试下面的聚合
在这里,首先你需要输入$limit
从聚合集合中获取单个文档... 然后 $facet
在同一组输入文档的单个阶段内处理多个聚合管道...现在需要执行 $lookup
聚合以从限制为 5 和 10 的其他集合中获取数据...连接从 $facet
获取的两个数组使用 $concatArrays
然后简单地 $unwind
并使用 $replaceRoot
将其替换为新的根 data
db.collection.aggregate([
{ "$limit": 1 },
{ "$facet": {
"collectionA": [
{ "$lookup": {
"from": Collection.name,
"pipeline": [
{ "$limit": 5 }
],
"as": "collectionA"
}},
{ "$project": { "collectionA": 1, "_id": 0 }},
{ "$unwind": "$collectionA" },
{ "$replaceRoot": { "newRoot": "$collectionA" } }
],
"collectionB": [
{ "$lookup": {
"from": Collection.name,
"pipeline": [
{ "$limit": 10 }
],
"as": "collectionB"
}},
{ "$project": { "collectionB": 1, "_id": 0 }},
{ "$unwind": "$collectionB" },
{ "$replaceRoot": { "newRoot": "$collectionB" } }
]
}},
{ "$project": {
"data": {
"$concatArrays": [ "$collectionA", "$collectionB" ]
}
}},
{ "$unwind": "$data" },
{ "$replaceRoot": { "newRoot": "$data" } }
// Here you can perform your other operations //
])
关于mongodb - 使用聚合合并两个单独集合的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51148906/