Era*_*bir 6 mongoose mongodb mongodb-query aggregation-framework
我正在尝试创建一个聚合管道 -$lookup仅从另一个集合接收不等于特定 _id 的项目
例如 :
诊所集合:
{_id:1,name:'some name1'}
{_id:2,name:'some name2'}
{_id:3,name:'some name3'}
Run Code Online (Sandbox Code Playgroud)
商业收藏:
{_id:1,name:"some business name",clinics:[1,2,3]}
Run Code Online (Sandbox Code Playgroud)
我的聚合管道查询:
db.business.aggregate([
{$match: {_id: mongoose.Types.ObjectId(businessId)}},
{$lookup:
{from: "ClinicsCollection", localField: "clinics", foreignField: "_id", as: "clinics"}},
]
Run Code Online (Sandbox Code Playgroud)
我想过滤所有不等于特定 ID 号的诊所,比如 _id : 1
预期结果 :
clinics :[
{_id:2,name:'some name2'}
{_id:3,name:'some name3'}
]
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
谢谢
您可以将下面的内容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"
}}
])
Run Code Online (Sandbox Code Playgroud)