Syntax error How do you compare two fields in MongoDB while performing an operation on one of them?

How do you compare two fields in MongoDB while performing an operation on one of them?



To compare two fields, use $where in MongoDB. Let us first create a collection with documents −

> db.demo7.insertOne({"FirstName1":"JOHN","FirstName2":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0ccd1a25ddae1f53b6222f")
}
> db.demo7.insertOne({"FirstName1":"Carol","FirstName2":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0ccd2725ddae1f53b62230")
}
> db.demo7.insertOne({"FirstName1":"bob","FirstName2":"BOB"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0ccd3225ddae1f53b62231")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.demo7.find();

This will produce the following output −

{ "_id" : ObjectId("5e0ccd1a25ddae1f53b6222f"), "FirstName1" : "JOHN", "FirstName2" : "John" }
{ "_id" : ObjectId("5e0ccd2725ddae1f53b62230"), "FirstName1" : "Carol", "FirstName2" : "Mike" }
{ "_id" : ObjectId("5e0ccd3225ddae1f53b62231"), "FirstName1" : "bob", "FirstName2" : "BOB" }

Here is the query to compare two fields while performing an operation on one of them −

> db.demo7.find({$where: "this.FirstName1.toLowerCase() == this.FirstName2.toLowerCase()"});

This will produce the following output −

{ "_id" : ObjectId("5e0ccd1a25ddae1f53b6222f"), "FirstName1" : "JOHN", "FirstName2" : "John" }
{ "_id" : ObjectId("5e0ccd3225ddae1f53b62231"), "FirstName1" : "bob", "FirstName2" : "BOB" }
Updated on: 2020-04-01T14:06:46+05:30

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements