How do you test if two external values are equal in a MongoDB criteria object?


To test the values, use $type. Let us create a collection with documents −

> db.demo211.insertOne({id:101,"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e298203d395bdc21346fa")
}
> db.demo211.insertOne({id:102,"Name":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e2a5403d395bdc21346fb")
}

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

> db.demo211.find();

This will produce the following output −

{ "_id" : ObjectId("5e3e298203d395bdc21346fa"), "id" : 101, "Name" : "Chris" }
{ "_id" : ObjectId("5e3e2a5403d395bdc21346fb"), "id" : 102, "Name" : null }

Following is the query to test if two external values are equal in a MongoDB criteria object −

> v1=200;
200
> v2=200;
200
> db.demo211.find({Name : 'Chris', Name : { $type : 1 + (v1 === v2) }});

This will produce the following output −

{ "_id" : ObjectId("5e3e298203d395bdc21346fa"), "id" : 101, "Name" : "Chris" }

Updated on: 27-Mar-2020

45 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements