다음은 일부 데이터가있는 내 스키마의 예입니다.
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"는 각 배열에 하나만있는 경우에만 작동합니다. 찾기 위해 모든 항목을 반복 할 필요없이 각 배열에 여러 항목이있는 경우 어떻게해야합니까?
더 자세한 정보가 필요하면 알려주세요.
통합 프레임 워크는 위치 운영자가 당신을 실패합니다 중첩 배열에 물건을 찾기위한 좋은 :
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) {
}
)
를 $first
사용할 때 문서에 다른 필드를 유지하는 것과 같은 다른 집계 연산자도 참조 하세요 $group
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다