Mongodb: $expr comparing two elements of same array in same document

Viewed 90

I have some documents with an array v containing exactly 2 objects with two numbers a and b as properties. I want to filter in an aggregation the documents where the two objects in the array have the same b value.

for instance, having this document:

[
  {
    "v": [
      {
        "a": 1,
        "b": 1
      },
      {
        "a": 1,
        "b": 2
      }
    ]
  }
]

and this query:

db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$eq": [
          "$v.0.b",
          "$v.1.b"
        ]
      }
    }
  }
])

The document should not pass, because it has two diff values (1 and 2) for b, but it eventually passes. Why?

Here is the playground: https://mongoplayground.net/

1 Answers

You should use the $arrayElemAt operator whenever you are referencing an object inside an array by its index.

The below query is what you are looking for.

db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$eq": [
          {
            "$arrayElemAt": [
              "$v.b",
              0  // References Array Index `0`
            ]
          },
          {
            "$arrayElemAt": [
              "$v.b",
              1  // References Array Index `1`
            ]
          },
        ]
      }
    }
  }
])
Related