How to compare field values in MongoDB?


You can use $where operator to compare field values in MongoDB. Let us first create a collection with documents

> db.comparingFieldDemo.insertOne({"Value1":30,"Value2":40});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c99ed2d6669774125246e")
}
> db.comparingFieldDemo.insertOne({"Value1":60,"Value2":70});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c99f62d6669774125246f")
}
> db.comparingFieldDemo.insertOne({"Value1":160,"Value2":190});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c99ff2d66697741252470")
}
> db.comparingFieldDemo.insertOne({"Value1":200,"Value2":160});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c9a0b2d66697741252471")
}

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

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

This will produce the following output

{
   "_id" : ObjectId("5c9c99ed2d6669774125246e"),
   "Value1" : 30,
   "Value2" : 40
}
{
   "_id" : ObjectId("5c9c99f62d6669774125246f"),
   "Value1" : 60,
   "Value2" : 70
}
{
   "_id" : ObjectId("5c9c99ff2d66697741252470"),
   "Value1" : 160,
   "Value2" : 190
}
{
   "_id" : ObjectId("5c9c9a0b2d66697741252471"),
   "Value1" : 200,
   "Value2" : 160
}

Following is the query to find by comparing field values.

> db.comparingFieldDemo.find({ $where: "this.Value1 > this.Value2" } );

This will produce the following output

{ "_id" : ObjectId("5c9c9a0b2d66697741252471"), "Value1" : 200, "Value2" : 160 }

Let us see another query

> db.comparingFieldDemo.find({ $where: "this.Value1 < this.Value2" } );

This will produce the following output

{ "_id" : ObjectId("5c9c99ed2d6669774125246e"), "Value1" : 30, "Value2" : 40 }
{ "_id" : ObjectId("5c9c99f62d6669774125246f"), "Value1" : 60, "Value2" : 70 }
{ "_id" : ObjectId("5c9c99ff2d66697741252470"), "Value1" : 160, "Value2" : 190 }

Updated on: 30-Jul-2019

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements