Christian Dechery
Christian Dechery

Reputation: 876

Matching documents with two values in nested array

So, I have the following structure in some documents:

{
  "Group": [
    {
      "data": {
        "field1": "VALUE1",
        "otherfield": "XXXX"
      }
    },
    {
      "data": {
        "field1": "VALUE2",
        "otherfield": "YYYYY"
      }
    }
  ]
}

The size of the Group array can be either 0, 1 or 2 in size. What I need to to is match the documents which contains both of VALUE1 and VALUE2 for field1. Couldn't find a suitable answer in here for this specific case.

I tried using $elemMatch but it will not work to bring only documents with both values. That is, it will work like an or not and.

Upvotes: 1

Views: 119

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You can use the $all array query operator with dot notation for this:

db.test.find({'Group.data.field1': {$all: ['VALUE1', 'VALUE2']}})

The $all operator selects the documents where the value of a field is an array that contains all the specified elements.

Upvotes: 2

Related Questions