0

We have the following schema for a MongoDb document. I want to display only the items with the flag "Display" set to true.

{
  id: 123,
  properties : [ 
     {name : "Name", value: "Value"},
     {name : "Description", value: "A description of the item"},
     {name : "Display", value: true}
 ]

}

I am not able to figure out how to do this in MongoDB. Any help would be greatly appreciated.

Parthasarathy
  • 2,698
  • 1
  • 12
  • 14

1 Answers1

1

To match the full array item you need to use the $elemMatch operator.

db.col.find({properties : {$elemMatch : {name : "Display", value : true}}});

This way, only a document with an array item that matches all of the conditions at the same time will be returned.

The query

db.col.find({"properties.name" : "Display", "properties.value" : true});

will match any combination in the array items.

For instance, the following document would also be returned in this case:

{
    id: 123,
    properties : [
        {name : "Name", value: "Value"},
        {name : "Description", value: "A description of the item"},
        {name : "Display", value: false},
        {name : "AnotherOne", value: true}
    ]
}
joao
  • 4,067
  • 3
  • 33
  • 37