我有以下查询,
MyModel.aggregate([
{
$project: {
field: 1,
}
},
{
$lookup: {
from: "AnotherModel",
localField: "_id",
foreignField: "someField",
as: "field"
},
},
{
$unwind: {
path: "$_id"
}
}
])
此作品已执行,但未如预期。在AnotherModel
中,有一个名为show
的字段,我希望此查询返回MyModel
集合,只有在show
上将AnotherModel
设置为true的情况下。我尝试过,
MyModel.aggregate([
{
$project: {
field: 1,
}
},
{
$lookup: {
from: "AnotherModel",
localField: "_id",
foreignField: "someField",
as: "field"
},
$where: {
show: true // <-- this part
}
},
{
$unwind: {
path: "$_id"
}
}
])
但是那引发了一个错误。我该如何实现?
MyModel.aggregate([
{
$project: {
field: 1
}
},
{
$lookup: {
from: "AnotherModel",
let: {
id: "$_id"
},
pipeline: [
{
$match: {
show: true,
$expr: {
$eq: [
"$someField",
"$$id"
]
}
}
}
],
as: "field"
}
},
{
$unwind: {
path: "$_id"
}
}
])
MongoPlayground