Compare multiple properties in MongoDB?


To compare multiple properties, use the $where operator. Let us first create a collection with documents −

> dbcomparingMultiplePropertiesDemoinsertOne({"Values":[10,70,60]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cf228fcb64a577be5a2bc0a")
}

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

> dbcomparingMultiplePropertiesDemofind()pretty();

This will produce the following document −

{
   "_id" : ObjectId("5cf228fcb64a577be5a2bc0a"),
   "Values" : [
      10,
      70,
      60
   ]
}

Case 1: If condition becomes true then you will get an array otherwise nothing will get displayed Following is the query to compare multiple properties in MongoDB.

> dbcomparingMultiplePropertiesDemofind({ $where : "thisValues[1] > thisValues[2]" });

This will produce the following document since 70 > 60 −

{ "_id" : ObjectId("5cf228fcb64a577be5a2bc0a"), "Values" : [ 10, 70, 60 ] }

Case 2: If condition becomes false then nothing will get displayed Following is the query to compare multiple properties in MongoDB −

> dbcomparingMultiplePropertiesDemofind({ $where : "thisValues[1] < thisValues[2]" });

For false condition, data won’t get displayed since 70 < 60 is false.

raja
Published on 14-Jun-2019 14:45:25
Advertisements