MongoDB query condition to compare two fields?

MongoDBDatabaseBig Data Analytics

You can use $where operator along with find() method to compare two fields in MongoDB. The syntax is as follows:

db.yourCollectionName.find({$where:”yourCondition”}).pretty();

To understand the above syntax, let us create a collection with some documents. The query to create a collection with documents is as follows:

>db.compareTwoFields.insert({"Id":1,"FullName":{"FirstName":"John","LastName":"Smith"},
"BranchName":"ComputerScience"});
WriteResult({ "nInserted" : 1 })

>db.compareTwoFields.insert({"Id":2,"FullName":{"FirstName":"Smith","LastName":"Smith"},
"BranchName":"Civil"});
WriteResult({ "nInserted" : 1 })

>db.compareTwoFields.insert({"Id":3,"FullName":{"FirstName":"David","LastName":"Smith"},
"BranchName":"Mechanical"});
WriteResult({ "nInserted" : 1 })

Now you can display all documents from a collection with the help of find() method. The query is as follows:

> db.compareTwoFields.find().pretty();

The following is the output:

{
   "_id" : ObjectId("5c6c237568174aae23f5ef64"),
   "Id" : 1,
   "FullName" : {
      "FirstName" : "John",
      "LastName" : "Smith"
   },
   "BranchName" : "ComputerScience"
}
{
   "_id" : ObjectId("5c6c239868174aae23f5ef65"),
   "Id" : 2,
   "FullName" : {
      "FirstName" : "Smith",
      "LastName" : "Smith"
   },
   "BranchName" : "Civil"
}
{
   "_id" : ObjectId("5c6c23b468174aae23f5ef66"),
   "Id" : 3,
   "FullName" : {
      "FirstName" : "David",
      "LastName" : "Smith"
   },
   "BranchName" : "Mechanical"
}

The following is the query to compare two fields in MongoDB:

>db.compareTwoFields.find({$where:"this.FullName.FirstName==this.FullName.LastName"}).
pretty();

The following is the output:

{
   "_id" : ObjectId("5c6c239868174aae23f5ef65"),
   "Id" : 2,
   "FullName" : {
      "FirstName" : "Smith",
      "LastName" : "Smith"
   },
   "BranchName" : "Civil"
}
raja
Published on 18-Mar-2019 11:10:03
Advertisements