3

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.

1 Answer 1

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

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"}
])
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the answer Roman. But what I need is not to select all the items. Sorry if I was not clear, but what I need is to specify the item_ids of the items which I need the data from.
@Sparky ok, see updated, we'll see if I understood you now :). You have to specify items in the first parameter of find.
I think you understand what I need now, but the updated query is also giving me all the items in the given organization (_id: 5) :(
@Sparky ok, 3rd attempt, if you want to filter out some elements from array, I think you still need aggregation framework :), see updated
Thanks @Roman, its working :) :) Thanks a lot. 1 more lil doubt too. Currently the output has item_id only. What if I need to get a bunch of other properties also about the returned items, say item_id and item_name? Can u please please update ur answer?? :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.