您可以使用 $lookup 运算符首先从 collectionA 对 collectionB 进行连接,然后使用 $unwind 展平从结果返回的单元素数组 strong> 然后使用 $redact 管道对文档进行文档级别的编辑
匹配指定条件的使用$$KEEP系统变量保留,不满足条件的使用$$PRUNE丢弃。最后,您需要运行以下聚合管道:
var exchangeRate = 1.5;
db.collectionA.aggregate([
{ "$match": { "price": { "$exists": true }, "name": { "$exists": true } } },
{
"$lookup": {
"from": "collectionB",
"localField": "name",
"foreignField": "name",
"as": "collectionB"
}
},
{ "$unwind": "$collectionB" },
{
"$redact": {
"$cond": [
{
"$gt": [
"$price", {
"$add": [
{ "$multiply": [ "$collectionB.price", exchangeRate ] },
4
]
}
]
},
"$$KEEP",
"$$PRUNE"
]
}
}
])
Robomongo 演示
填充测试集合:
db.collectionA.insert([
{ "name": "item1", "price": 30 },
{ "name": "item2", "price": 20 }
])
db.collectionB.insert([
{ "name": "item1", "price": 50 },
{ "name": "item2", "price": 10 }
])
运行和调试聚合管道:
样本输出:
{
"_id" : ObjectId("58ad50a429b2961777f91c95"),
"name" : "item2",
"price" : 20,
"collectionB" : {
"_id" : ObjectId("58ad50a429b2961777f91c97"),
"name" : "item2",
"price" : 10
}
}