2013-08-31 57 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 * “10” OR与* ITEM_ID * “11”。

我需要的是是组织“abc”的item_id 10和11的获取值。请帮忙。

回答

7

UPDATE2

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.find({ 
    "_id": 5, 
    items: {$elemMatch: {"item_id": {$in: ["10", "11"]}}} 
}) 

看起来你需要aggregation framework,特别$unwind操作:

db.organizations.aggregate([ 
    {$match:{_id:5}}, // you can remove this to return all your data 
    {$unwind:"$items"} 
]) 
+0

感谢您的罗马答案。但我需要的不是选择所有的项目。对不起,如果我不清楚,但我需要的是指定我需要的数据项的'item_id's。 – Sparky

+0

@Sparky好的,看到更新后,我们会看看我现在是否了解你:)。你必须在'find'的第一个参数中指定'items'。 –

+0

我想你明白我现在需要什么,但更新后的查询也给了我给定组织中的所有项目(_id:5):( – Sparky