How to compare attributes of different objects in MongoDB object array?


To compare attributes, use $let along with $indexOfArray. Let us first create a collection with documents −

> db.demo366.insertOne(
...    {
...
...       "Name" : "Chris",
...       "details" : [
...       {
...          "Id" : "John1",
...          "value" : "test"
...       },
...       {
...          "Id" : "John2",
...          "value" : 18
...       },
...       {
...          "Id" : "John3",
...          "value" : 20
...       }
...    ]}
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57ddd92ae06a1609a00ae7")
}

Display all documents from a collection with the help of find() method −

> db.demo366.find();

This will produce the following output −

{
   "_id" : ObjectId("5e57ddd92ae06a1609a00ae7"), "Name" : "Chris", "details" : [
      { "Id" : "John1", "value" : "test" }, { "Id" : "John2", "value" : 18 },
      { "Id" : "John3", "value" : 20 }
   ]
}

Following is the query to compare attributes of different objects in the MongoDB object array −

> db.demo366.find(
...    {"$expr":{
...       "$let":{
...          "vars":{
...             "john2":{"$arrayElemAt":["$details",{"$indexOfArray":["$details.Id","John2"]}]},
...             "john3":{"$arrayElemAt":["$details",{"$indexOfArray":["$details.Id","John3"]}]}
...    },
...    "in":{"$lt":["$$john2.value","$$john3.value"]}}
... }})

This will produce the following output −

{
   "_id" : ObjectId("5e57ddd92ae06a1609a00ae7"), "Name" : "Chris", "details" : [
      { "Id" : "John1", "value" : "test" }, { "Id" : "John2", "value" : 18 },
      { "Id" : "John3", "value" : 20 }
   ] 
}

Updated on: 02-Apr-2020

498 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements