
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
Match Between Fields in MongoDB Aggregation Framework
You can use $cmp operator for this. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.matchBetweenFieldsDemo.insertOne({"FirstValue":40,"SecondValue":70}); { "acknowledged" : true, "insertedId" : ObjectId("5c92c9625259fcd19549980d") } > db.matchBetweenFieldsDemo.insertOne({"FirstValue":20,"SecondValue":5}); { "acknowledged" : true, "insertedId" : ObjectId("5c92c96b5259fcd19549980e") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.matchBetweenFieldsDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c92c9625259fcd19549980d"), "FirstValue" : 40, "SecondValue" : 70 } { "_id" : ObjectId("5c92c96b5259fcd19549980e"), "FirstValue" : 20, "SecondValue" : 5 }
Here is the query to $match between fields in aggregation framework −
> db.matchBetweenFieldsDemo.aggregate([ ... {$project: { ... ... firstGreaterThanOrNot: {$cmp: ['$FirstValue', '$SecondValue']} ... }}, ... {$match: {firstGreaterThanOrNot:{$gt: 0}}} ... ]);
The following is the output −
{ "_id" : ObjectId("5c92c96b5259fcd19549980e"), "firstGreaterThanOrNot" : 1 }
Advertisements