我正在尝试建立一个汇总管道-$lookup
以从另一个管道接收
仅收集不等于特定_id
例如:
ClinicsCollection:
{_id:1,name:'some name1'}
{_id:2,name:'some name2'}
{_id:3,name:'some name3'}
BusinessCollection:
{_id:1,name:"some business name",clinics:[1,2,3]}
我的聚合管道查询:
db.business.aggregate([
{$match: {_id: mongoose.Types.ObjectId(businessId)}},
{$lookup:
{from: "ClinicsCollection", localField: "clinics", foreignField: "_id", as: "clinics"}},
]
我想过滤所有不等于特定ID号的诊所,比如说_id:1
预期结果:
clinics :[
{_id:2,name:'some name2'}
{_id:3,name:'some name3'}
]
我该如何实现?
谢谢
答案 0 :(得分:1)
您可以在aggregation
以下与mongodb 3.6 及更高版本
您需要像在第一阶段中对父集合一样使用$match
与子集合。
db.BusinessCollection.aggregate([
{ "$match": { "clinics": { "$type": "array" }}},
{ "$lookup": {
"from": "ClinicsCollection",
"let": { "clinics": "$clinics" },
"pipeline": [
{ "$match": {
"$expr": {
"$and": [
{ "$in": ["$_id", "$$clinics"] },
{ "$not": { "$eq": ["$_id", 1] }}
]
}
}}
],
"as": "clinics"
}}
])
答案 1 :(得分:0)
您可以尝试对低于3.6的mongodb版本进行以下汇总
db.business.aggregate([
{$match : {_id : 1}},
{$lookup : {from : "clinics", localField : "clinics", foreignField : "_id", as : "clinics"}},
{$addFields : {clinics : {$filter : {input : "$clinics", as : "c", cond : {$ne : ["$$c._id", 1]}}}}}
]).pretty()
结果
{ "_id" : 1, "name" : "some business name", "clinics" : [ { "_id" : 2, "name" : "some name2" }, { "_id" : 3, "name" : "some name3" } ] }