2013-08-31 3 views
3

를 사용하여 배열에서 여러 하위 dicuments를 선택 : -

{ 
    _id: 5, 
    "org_name": "abc", 
    "items": [ 
    { 
     "item_id": "10", 
     "data": [ 
     // Values goes here 
     ] 
    }, 
    { 
     "item_id": "11", 
     "data": [ 
     // Values goes here 
     ] 
    } 
    ] 
}, 

// Another sub document 
{ 
    _id: 6, 
    "org_name": "sony", 
    "items": [ 
    { 
     "item_id": "10", 
     "data": [ 
     // Values goes here 
     ] 
    }, 
    { 
     "item_id": "11", 
     "data": [ 
     // Values goes here 
     ] 
    } 
    ] 
} 

각 하위 문서는 개별 조직에 해당하는 각각의 조직은 그들 itemsarray있다.

내가 원하는 것은 items 배열에서 선택 개별 요소를 얻으려면 item_id을 제공하는 것입니다.

db.organizations.find({"_id": 5}, {items: {$elemMatch: {"item_id": {$in: ["10", "11"]}}}}) 

하지만 * ITEM_ID * "11"로 OR * ITEM_ID * "10"으로 항목 목록을 항목 목록을 반환 하나되는 -을 :

이미이 시도.

내가 필요한 것은은 "abc"조직의 item_id 10과 11 모두에 대한 값을 가져옵니다. 도와주세요.

답변

7

갱신 2 :

db.organizations.aggregate([ 
    // you can remove this to return all your data 
    {$match:{_id:5}}, 
    // unwind array of items 
    {$unwind:"$items"}, 
    // filter out all items not in 10, 11 
    {$match:{"items.item_id":{"$in":["10", "11"]}}}, 
    // aggregate again into array 
    {$group:{_id:"$_id", "items":{$push:"$items"}}} 
]) 

갱신 :

db.organizations.aggregate([ 
    {$match:{_id:5}}, // you can remove this to return all your data 
    {$unwind:"$items"} 
]) 
: 당신이 aggregation framework이 필요한 것처럼

db.organizations.find({ 
    "_id": 5, 
    items: {$elemMatch: {"item_id": {$in: ["10", "11"]}}} 
}) 

는, 특히 $unwind 운영자 보이는

+0

답장을 보내 주셔서 감사합니다. 하지만 내가 필요한 것은 * 모든 항목을 선택하지 않는 것입니다. 미안하지만 분명하지 않다면 필요한 것은 데이터가 필요한 항목의 'item_id'를 지정하는 것입니다. – Sparky

+0

@ Sparky ok, 업데이트 됨, 내가 지금 당신을 이해하는지 알 수 있습니다 :). 'find'의 첫 번째 매개 변수에'items'를 지정해야합니다. –

+0

내가 지금 필요한 것은 무엇인지 이해하고 있다고 생각하지만 업데이트 된 쿼리는 주어진 조직 (_id : 5)의 모든 항목을 제공합니다. ( – Sparky