CLOVIS
CLOVIS

Reputation: 998

MongoDB query on specific child

I've got a document that contains an array of elements. I'd like to find specific entries in that document.

Example entry 1:

{
  "c": [
    {
      "k": "1",
      "v": "1",
    },
    {
      "k": "2",
      "v": "2",
    },
  ]
}

Example entry 2:

{
  "c": [
    {
      "k": "1",
      "v": "2",
    },
    {
      "k": "2",
      "v": "1",
    },
  ]
}

I'd like to find all entries that have a k that is 1, and a matching v that is 1 (here, the first entry matches, but the second one doesn't, because the v that has the value of 1 is not the same object as the k valued 1).

So far, I found the query:

{
  "$and": [
    {"c.k": "1"},
    {"c.v": "1"}
  ]
}

However, that returns both entries, not just the first one. Is there a way to tell MongoDB that both constraints should apply to the same item in the array, and not just to any item?

Upvotes: 0

Views: 512

Answers (1)

hhharsha36
hhharsha36

Reputation: 3349

As suggested by @turiviashal, make use of the $elemMatch operator which matches documents with will match all the key conditions in at least one object.

db.collection.aggregate([
  {
    "$match": {
      "c": {
        "$elemMatch": {
          "k": "1",
          "v": "1",
          
        }
      }
    }
  }
])

Mongo Playground Example

Upvotes: 1

Related Questions