- 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
Filter documents in MongoDB using simple query?
You can use $match. The $match filters the documents to pass only the documents that match the specified condition to the next pipeline stage. Let us create a collection with documents −
> db.demo629.insertOne( ... { ... ... "Subject": [ ... "MySQL", ... "MongoDB" ... ], ... "details": [ ... { ... Name:"Chris", ... "Marks":78 ... }, ... { Name:"David", ... "Marks":89 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9ae9f56c954c74be91e6b9") }
Display all documents from a collection with the help of find() method −
> db.demo629.find();
This will produce the following output −
{ "_id" : ObjectId("5e9ae9f56c954c74be91e6b9"), "Subject" : [ "MySQL", "MongoDB" ], "details" : [ { "Name" : "Chris", "Marks" : 78 }, { "Name" : "David", "Marks" : 89 } ] }
Following is the query to filter documents in MongoDB using simple query −
> db.demo629.aggregate([ ... {"$unwind": "$details"}, ... {"$match": {"details.Name": 'Chris', "Subject": {"$in":["Java","MySQL","Python","C","C++"]}}}, ... {"$project": {"details": 1, "_id": 0}} ... ]);
This will produce the following output −
{ "details" : { "Name" : "Chris", "Marks" : 78 } }
Advertisements