MongoDB query condition on comparing 2 fields?


To query condition on comparing 2 fields, use the following syntax −

db.yourCollectionName.find( { $where: function() { return this.yourFirstFieldName < this.yourSecondFieldName } } ).pretty();

To understand the syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.comparingTwoFieldsDemo.insertOne({"StudentName":"John","StudentAge":21,"StudentMathMarks":99,"StudentPhysicsMarks":98});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ac09e6cea1f28b7aa0807")
}
> db.comparingTwoFieldsDemo.insertOne({"StudentName":"Carol","StudentAge":22,"StudentMathMarks":79,"StudentPhysicsMarks":89});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ac0b46cea1f28b7aa0808")
}
> db.comparingTwoFieldsDemo.insertOne({"StudentName":"David","StudentAge":24,"StudentMathMarks":39,"StudentPhysicsMarks":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ac0c96cea1f28b7aa0809")
}
> db.comparingTwoFieldsDemo.insertOne({"StudentName":"Bob","StudentAge":23,"StudentMathMarks":87,"StudentPhysicsMarks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ac0e06cea1f28b7aa080a")
}

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

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

The following is the output −

{
   "_id" : ObjectId("5c8ac09e6cea1f28b7aa0807"),
   "StudentName" : "John",
   "StudentAge" : 21,
   "StudentMathMarks" : 99,
   "StudentPhysicsMarks" : 98
}
{
   "_id" : ObjectId("5c8ac0b46cea1f28b7aa0808"),
   "StudentName" : "Carol",
   "StudentAge" : 22,
   "StudentMathMarks" : 79,
   "StudentPhysicsMarks" : 89
}
{
   "_id" : ObjectId("5c8ac0c96cea1f28b7aa0809"),
   "StudentName" : "David",
   "StudentAge" : 24,
   "StudentMathMarks" : 39,
   "StudentPhysicsMarks" : 45
}
{
   "_id" : ObjectId("5c8ac0e06cea1f28b7aa080a"),
   "StudentName" : "Bob",
   "StudentAge" : 23,
   "StudentMathMarks" : 87,
   "StudentPhysicsMarks" : 78
}

Here is the query to condition on comparing 2 fields −

> db.comparingTwoFieldsDemo.find( { $where: function() { return this.StudentMathMarks < this.StudentPhysicsMarks } } ).pretty();

The following is the output −

{
   "_id" : ObjectId("5c8ac0b46cea1f28b7aa0808"),
   "StudentName" : "Carol",
   "StudentAge" : 22,
   "StudentMathMarks" : 79,
   "StudentPhysicsMarks" : 89
}
{
   "_id" : ObjectId("5c8ac0c96cea1f28b7aa0809"),
   "StudentName" : "David",
   "StudentAge" : 24,
   "StudentMathMarks" : 39,
   "StudentPhysicsMarks" : 45
}

Updated on: 30-Jul-2019

264 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements