
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
Advertisements