抱歉,我的英语不好......
如何使用mongoose查找子匹配?
我的查询是
categorys.aggregate([{
"$sort": {
"order": 1,
"id": 1
}
},
{
"$lookup": {
"localField": "id",
"from": "categorys",
"foreignField": "parentId",
"as": "child"
}
},
{
"$match": {
see: true,
depth: 1
}
}
]).exec(function(err, Categorys)
是结果
{
"_id": "596e237c414f2137b0c4e9c2",
"id": 3,
"name": "DB",
"address": "DB",
"parentId": 0,
"depth": 1,
"see": true,
"__v": 0,
"child": [{
"_id": "596e24701e1bd30dc415b894",
"id": 5,
"name": "Mongodb",
"address": "Mongodb",
"parentId": 3,
"depth": 2,
"see": true,
"__v": 0
},
{
"_id": "596e24821e1bd30dc415b895",
"id": 6,
"name": "mssql",
"address": "mssql",
"parentId": 3,
"depth": 2,
"see": false,
"__v": 0
}
]
}]
我看不到mssql的结果(参见:false)匹配怎么样? 救救我!
答案 0 :(得分:1)
如果要在$filter
数组中匹配,可以在$project
阶段使用child
。像吼叫一样。
categorys.aggregate([
{
"$sort": {
"order": 1,
"id": 1
}
},
{
"$lookup": {
"localField": "id",
"from": "categorys",
"foreignField": "parentId",
"as": "child"
}
},
{
$project: {
name: 1,
address: 1,
// ... as you need
child: {
$filter: {
input: "$child",
as: "item",
cond: {
$and: [
{$eq: ["$$item.see", true]},
{$eq: ["$$item.depth", 2]}
]
}
}
}
}
}
])
N.B:如果你想对"depth":1,"see":true,
之类的父字段使用匹配条件,那么你应该在$match
之前使用$lookup
阶段
categorys.aggregate([
{$match:{//parent field match condition first}},
{$sort:{}},
{$lookup:{}},
{$project:{//for child}}
]);