我在猫鼬中有以下聚合代码,它运行正常,但我希望过滤结果:
Mov.aggregate(
[
{ $sort: { _id: 1, car_id: 1, area: 1 } },
{
$group:
{
_id: "$car_id",
lastLocation: { $last: "$area" }
}
},
{
$lookup: {
from: Car.collection.name,
"localField": "_id",
"foreignField": "_id",
as: 'cars'
}
},
]
)
.then(movs => {
res.send(movs);
}).catch(err => {
res.status(500).send({
message: err.message
});
});
如何在Car.collection.name
中过滤$lookup
中的{"active":true}
,而我只想获得装有{{1}}的汽车?
答案 0 :(得分:0)
您可以使用其他查找策略。以下是更新后的查询:
Mov.aggregate([{
$sort: {
"_id": 1,
"car_id": 1,
"area": 1
}
},
{
$group: {
_id: "$car_id",
lastLocation: {
$last: "$area"
}
}
},
{
$lookup: {
from: Car.collection.name,
let: {
"_id": "$_id"
},
pipeline: [{
$match: {
$expr: {
$eq: ["$_id", "$$_id"]
},
active: true
}
}],
"as": "cars"
}
}
]).then(movs => {
res.send(movs);
}).catch(err => {
res.status(500).send({
message: err.message
});
});
您可以检查以下链接,以获取有关此查找策略https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
的更多信息