模拟数据
city表
{
"_id": {
"$oid": "5f3b38a02e53c81ce4073d77"
},
"status": {
"$numberInt": "1"
},
"add_time": {
"$numberDouble": "1597716640324"
},
"title": "北京",
}
food表
cid与city表_id关联
{
_id:5f3a30c10210872e24d7ed0e,
status:1,
cid: 5f3b38a02e53c81ce4073d77
add_time:1597716657403,
food:"北京烤鸭",
__v:0,
sort:"1"
}
{
_id:2f3a0123ac210872e2ccc12eae,
status:0,
cid: 5f3b38a02e53c81ce4073d77
add_time:1597716657402,
food:"北京烤猪",
__v:0,
sort:"2"
},
{
_id:4f3a0123a12312342e2ccc12eae,
status:1,
cid: 5f3b38a02e53c81ce4073d77
add_time:1597716657402,
food:"北京烤羊",
__v:0,
sort:"2"
}
关联查询并筛选子集
使用$filter
对子集进行筛选, 获取status不为0的数据
//...省略
model.Food.aggregate([
{
$lookup: {
from: "city",
localField: "cid",
foreignField: "_id",
as: "foods",
},
},
{
$project: {
foods: {
$filter: {
input: '$foods',
as:'item',
cond: {$ne: ['$$item.status', 0]}
}
}
}
}
]);
查询结果
{
"_id": "5f3b38a02e53c81ce4073d77",
"status": 1
"add_time": "1597716640324",
"title": "北京",
"foods": [
{
_id:5f3a30c10210872e24d7ed0e,
status:1,
cid: 5f3b38a02e53c81ce4073d77
add_time:1597716657403,
food:"北京烤鸭",
__v:0,
sort:"1"
},
{
_id:4f3a0123a12312342e2ccc12eae,
status:1,
cid: 5f3b38a02e53c81ce4073d77
add_time:1597716657402,
food:"北京烤羊",
__v:0,
sort:"2"
}
]
}