9

I have a document containing nested array data. I tried hopelessly to filter the data using $elemMatch but I cannot figure out why it is not working.

{
'id' : 1,
'name' : 'test',
'modules' : [
    {
        name: 'foo',
        mandatory: false,
        group: [
            {
                name: g1
            }]
    },
    {
        name: 'bar',
        mandatory: false,
        group: [
            {
                name: g2
            }]
    }]
}

I tried using this query:

db.test.find(
{
  modules: {
            $elemMatch: {
                 name: "foo",
            }
  }
}

But it keeps returning all the modules. If I use mandatory: true it returns nothing, which seems to indicates it works. Any idea what am I doing wrong? Thanks!

1
  • Querying is very easy but what about updates? Commented Jan 27, 2014 at 19:22

1 Answer 1

19

Your query is simply returning all docs that contain a modules element where name == 'foo'. To use $elemMatch to filter the output, you need to use it in the projection argument of the find call instead of part of the query:

db.test.find({}, {modules: {$elemMatch: {name: 'foo'}}})

To combine both concepts, you can reference the index of the array element matched in the query with $:

db.test.find({modules: {$elemMatch: {name: 'foo'}}}, {'modules.$': 1})

Either way returns:

{
  "_id": ObjectId("..."),
  "modules": [
    {
      "name": "foo",
      "mandatory": false,
      "group": [
        {
          "name": "g1"
        }
      ]
    }
  ]
}

If you need other fields included in the output, add them to the projection object (e.g. name: 1).

Sign up to request clarification or add additional context in comments.

1 Comment

Is it possible to chain the elemMatch? For example to filter on the "group" list on the name as well?

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.