在聚合函数中添加限制和跳过后,$lookup不起作用



我是mongodb的新手,我很困惑为什么我的查找在下面的场景中不起作用

//查找不起作用

[
{
"$match":{
"is_active":{
"$eq":1
}
}
},
{
"$facet":{
"length":[
{
"$count":"total"
}
],
"data":[
{
"$skip":0
},
{
"$limit":10
}
]
}
},
{
"$lookup":{
"from":"offences",
"localField":"offences",
"foreignField":"offence_id",
"as":"offenceSetail"
}
},
{
"$project":{
"offences.is_active":0
}
},
{
"$replaceRoot":{
"newRoot":{
"$mergeObjects":[
{
"$arrayElemAt":[
"$offenceSetail",
0
]
},
"$$ROOT"
]
}
}
},
{
"$project":{
"offenceSetail":0
}
},
{
"$lookup":{
"from":"registers",
"localField":"user_id",
"foreignField":"id",
"as":"sender"
}
},
{
"$project":{
"registers.is_active":0
}
},
{
"$replaceRoot":{
"newRoot":{
"$mergeObjects":[
{
"$arrayElemAt":[
"$sender",
0
]
},
"$$ROOT"
]
}
}
},
{
"$project":{
"sender":0
}
}
],
"options":{
}
}

//查找正在进行

[
{
"$match":{
"is_active":{
"$eq":1
}
}
},
{
"$lookup":{
"from":"offences",
"localField":"offences",
"foreignField":"offence_id",
"as":"offenceSetail"
}
},
{
"$project":{
"offences.is_active":0
}
},
{
"$replaceRoot":{
"newRoot":{
"$mergeObjects":[
{
"$arrayElemAt":[
"$offenceSetail",
0
]
},
"$$ROOT"
]
}
}
},
{
"$project":{
"offenceSetail":0
}
},
{
"$lookup":{
"from":"registers",
"localField":"user_id",
"foreignField":"id",
"as":"sender"
}
},
{
"$project":{
"registers.is_active":0
}
},
{
"$replaceRoot":{
"newRoot":{
"$mergeObjects":[
{
"$arrayElemAt":[
"$sender",
0
]
},
"$$ROOT"
]
}
}
},
{
"$project":{
"sender":0
}
},
{
"$facet":{
"length":[
{
"$count":"total"
}
],
"data":[
{
"$skip":0
},
{
"$limit":10
}
]
}
}
],
"options":{
}
}

请帮我怎么解决。感谢

第一种情况下的查找不起作用,因为查找中指定的本地字段不存在。在$facet阶段之后,我们得到两个阵列,即lengthdata。我们需要将localField指定为data.offences

使用$facet,您将能够同时运行两个聚合。使用$facet得到的每个字段都表示单独的聚合管道,这就是为什么总是得到一个数组作为输出。

{
"$facet":{
"length":[
{
"$count":"total"
}
],
"data":[
{ "$skip":0 },
{ "$limit":10 }
]
}

}

您将得到两个数组,即长度和数据。示例:

{
"length" : [ 
{
"total" : 360
}
],
"data" : [ 
{
"_id" : ObjectId("5d5beae5662cdb57e2b80eff"),
"is_active": 1
}, 
...
]

}

因此,您必须先释放"数据"。然后进行查找操作。所以你可以做一些类似的事情

// After $facet
{
$unwind: "$data"
},
{
"$lookup":{
"from":"offences",
"localField":"data.offences",
"foreignField":"offence_id",
"as":"offenceSetail"
}
},
{
$unwind: "$offenceSetail"
}

最新更新