- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do you compare two fields in MongoDB while performing an operation on one of them?
To compare two fields, use $where in MongoDB. Let us first create a collection with documents −
> db.demo7.insertOne({"FirstName1":"JOHN","FirstName2":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5e0ccd1a25ddae1f53b6222f") } > db.demo7.insertOne({"FirstName1":"Carol","FirstName2":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5e0ccd2725ddae1f53b62230") } > db.demo7.insertOne({"FirstName1":"bob","FirstName2":"BOB"}); { "acknowledged" : true, "insertedId" : ObjectId("5e0ccd3225ddae1f53b62231") }
Following is the query to display all documents from a collection with the help of find() method −
> db.demo7.find();
This will produce the following output −
{ "_id" : ObjectId("5e0ccd1a25ddae1f53b6222f"), "FirstName1" : "JOHN", "FirstName2" : "John" } { "_id" : ObjectId("5e0ccd2725ddae1f53b62230"), "FirstName1" : "Carol", "FirstName2" : "Mike" } { "_id" : ObjectId("5e0ccd3225ddae1f53b62231"), "FirstName1" : "bob", "FirstName2" : "BOB" }
Here is the query to compare two fields while performing an operation on one of them −
> db.demo7.find({$where: "this.FirstName1.toLowerCase() == this.FirstName2.toLowerCase()"});
This will produce the following output −
{ "_id" : ObjectId("5e0ccd1a25ddae1f53b6222f"), "FirstName1" : "JOHN", "FirstName2" : "John" } { "_id" : ObjectId("5e0ccd3225ddae1f53b62231"), "FirstName1" : "bob", "FirstName2" : "BOB" }
Advertisements
To Continue Learning Please Login
Login with Google