Search code examples
mongodbmongodb-querymongodb-compass

MongoDB Compass - Compare array fields within same document


Hi I have a document with the structure as shown below:

{
  "_id": {
    "$oid": "5bc7a1d14cedfd0006445b10"
  },
  "externalId": {
    "$numberLong": "70285"
  },
  "passengers": [
    {
      "_id": {
        "$numberLong": "3757"
      },
      "name": "abc",
      "email": "[email protected]"
    },
    {
      "_id": {
        "$numberLong": "398"
      },
      "name": "abc n",
      "email": "[email protected]"
    }
  ]
}

Here I want to find all the documents where the first element of the passenger email is the same as the second element.

In MongoDB Compass I could use the filter to do like this:

{"passengers.0.email": "[email protected]"}

This gives me all the emails where the passenger with the first item has "[email protected]" as email. The same case is if I search for the second element.

But when I try to do the following

{"passengers.0.email": "passengers.1.email"}

It does not give me all docs where the first two items in the array have the same email. Is this possible using the MongoDB Compass?


Solution

  • You can work with $arrayElemAt operator to get the specific element in the array by index.

    db.collection.find({
      $expr: {
        $eq: [
          {
            $arrayElemAt: [
              "$passengers.email",
              0
            ]
          },
          {
            $arrayElemAt: [
              "$passengers.email",
              1
            ]
          }
        ]
      }
    })
    

    Demo @ Mongo Playground