MongoDB - How to check for equality in collection and in embedded document?


For this, check using $where in MongoDB. Let us create a collection with documents −

> db.demo292.insertOne({FirstName:"Chris",LastName:"Brown",
...   "Friend":{FirstName:"David","LastName":"Miller"}
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4c10aa5d93261e4bc9ea30")
}
> db.demo292.insertOne({FirstName:"John",LastName:"Doe",
...   "Friend":{FirstName:"Mike","LastName":"Doe"}
...}
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4c10dc5d93261e4bc9ea31")
}

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

>  db.demo292.find();

This will produce the following output −

{ "_id" : ObjectId("5e4c10aa5d93261e4bc9ea30"), "FirstName" : "Chris", "LastName" : "Brown", "Friend" : { "FirstName" : "David", "LastName" : "Miller" } }
{ "_id" : ObjectId("5e4c10dc5d93261e4bc9ea31"), "FirstName" : "John", "LastName" : "Doe", "Friend" : { "FirstName" : "Mike", "LastName" : "Doe" } }

Following is the query to check for equality in collection and in embedded document −

> db.demo292.find({$where: 'this.Friend.LastName === this.LastName'})

This will produce the following output −

{ "_id" : ObjectId("5e4c10dc5d93261e4bc9ea31"), "FirstName" : "John", "LastName" : "Doe", "Friend" : { "FirstName" : "Mike", "LastName" : "Doe" } }

Updated on: 31-Mar-2020

83 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements