以下是我的Schema示例,其中包含一些数据:
client {
menus: [{
sections: [{
items: [{
slug: 'some-thing'
}]
}]
}]
}
我试图像这样选择它:
Schema.findOne({ client._id: id, 'menus.sections.items.slug': 'some-thing' }).select('menus.sections.items.$').exec(function(error, docs){
console.log(docs.menus[0].sections[0].items[0].slug);
});
当然" docs.menus [0] .sections [0] .items [0] .slug"只有在每个数组中只有一个东西时才有效。如果每个数组中有多个项目而不必遍历所有内容以找到它,我该如何才能使这个工作?
如果您需要更多详情,请与我们联系。
答案 0 :(得分:1)
aggregation framework适用于在深层嵌套数组中查找位置运算符会使您失败的内容:
Model.aggregate(
[
// Match the "documents" that meet your criteria
{ "$match": {
"menus.sections.items.slug": "some-thing"
}},
// Unwind the arrays to de-normalize as documents
{ "$unwind": "$menus" },
{ "$unwind": "$menus.sections" },
{ "$unwind": "$menus.sections.items" }
// Match only the element(s) that meet the criteria
{ "$match": {
"menus.sections.items.slug": "some-thing"
}}
// Optionally group everything back to the nested array
// One step at a time
{ "$group": {
"_id": "$_id",
"items": { "$push": "$menus.sections.items.slug" }
}},
{ "$group": {
"_id": "$_id",
"sections": {
"$push": { "items": "$items" }
}
}},
{ "$group": {
"_id": "$_id",
"menus": {
"$push": { "sections": "$sections" }
}
}},
],
function(err,results) {
}
)