Sparky
Sparky

Reputation: 4879

MongoDB - Select multiple sub-dicuments from array using $elemMatch

I have a collection like the following:-

{
  _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
      ]
    }
  ]
}

Each sub document corresponds to individual organizations and each organization has an array of items in them.

What I need is to get the select individual elements from the items array, by providing item_id.

I already tried this:-

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

But it is returning either the item list with *item_id* "10" OR the item list with *item_id* "11".

What I need is is the get values for both item_id 10 and 11 for the organization "abc". Please help.

Upvotes: 3

Views: 3727

Answers (1)

roman
roman

Reputation: 117345

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"}}}
])

update:

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

old Looks like you need aggregation framework, particularly $unwind operator:

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

Upvotes: 7

Related Questions