Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
]
}Advertisements