
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
MongoDB Query to Find on Field Combination of Firstname and Lastname
For combination, use $concat and check the equality using $eq. Let us create a collection with documents −
> db.demo502.insertOne({"FirstName":"John","LastName":"Smith"});{ "acknowledged" : true, "insertedId" : ObjectId("5e875534987b6e0e9d18f56d") } > db.demo502.insertOne({"FirstName":"David","LastName":"Miller"});{ "acknowledged" : true, "insertedId" : ObjectId("5e87553e987b6e0e9d18f56e") } > db.demo502.insertOne({"FirstName":"John","LastName":"Doe"});{ "acknowledged" : true, "insertedId" : ObjectId("5e875543987b6e0e9d18f56f") }
Display all documents from a collection with the help of find() method −
> db.demo502.find();
This will produce the following output −
{ "_id" : ObjectId("5e875534987b6e0e9d18f56d"), "FirstName" : "John", "LastName" : "Smith" } { "_id" : ObjectId("5e87553e987b6e0e9d18f56e"), "FirstName" : "David", "LastName" : "Miller" } { "_id" : ObjectId("5e875543987b6e0e9d18f56f"), "FirstName" : "John", "LastName" : "Doe" }
Following is the query to find on field combination −
> db.demo502.aggregate( ... [ ... { "$redact": { ... "$cond": [ ... { "$eq": [ ... { "$concat": [ "$FirstName", " ", "$LastName" ] }, ... "John Doe" ... ]}, ... "$$KEEP", ... "$$PRUNE" ... ] ... }} ... ] ... )
This will produce the following output −
{ "_id" : ObjectId("5e875543987b6e0e9d18f56f"), "FirstName" : "John", "LastName" : "Doe" }
Advertisements