

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to filter some fields in objects and fetch a specific subject name value in MongoDB?
To filter and fetch, use projection along with MongoDB $filter and $match. Let us create a collection with documents −
> db.demo507.insertOne( ... { ... ... "Information": ... [ ... {"Name":"John","SubjectName":"MySQL"}, ... {"Name":"Bob","SubjectName":"MongoDB"}, ... {"Name":"Chris","SubjectName":"MySQL"}, ... {"Name":"David","SubjectName":"C++"} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8836d3987b6e0e9d18f577") }
Display all documents from a collection with the help of find() method −
> db.demo507.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e8836d3987b6e0e9d18f577"), "Information" : [ { "Name" : "John", "SubjectName" : "MySQL" }, { "Name" : "Bob", "SubjectName" : "MongoDB" }, { "Name" : "Chris", "SubjectName" : "MySQL" }, { "Name" : "David", "SubjectName" : "C++" } ] }
Following is the query to filter some fields in objects −
> db.demo507.aggregate([ ... {$match: {"Information.SubjectName" : "MySQL" } }, ... {$project: { ... _id:0, ... Information: { ... $filter: { ... input: '$Information', ... as: 'result', ... cond: {$eq: ['$$result.SubjectName', 'MySQL']} ... } ... } ... } ... },{$project: {Information: { SubjectName:1}}} ... ]);
This will produce the following output −
{ "Information" : [ { "SubjectName" : "MySQL" }, { "SubjectName" : "MySQL" } ] }
- Related Questions & Answers
- Fetch a specific column value (name) in MySQL
- Query an array in MongoDB to fetch a specific value
- How to query MongoDB a value with $lte, $in and $not to fetch specific values?
- Searching 2 fields at the same time to fetch a specific First Name and Last Name from a table in MySQL
- MongoDB aggregation to fetch documents with specific field value?
- How to compare two fields in aggregation filter with MongoDB?
- Update only specific fields in MongoDB?
- MongoDB query to sum specific fields
- Fetch specific field values in MongoDB
- Fetch specific multiple documents in MongoDB
- Using Filter to fetch specific data in SAP Crystal Reports
- Filter specific values from a MongoDB document
- Match MongoDB documents with field value greater than a specific number and fetch them?
- MongoDB collection query to exclude some fields in find()?
- Filter array of objects by a specific property in JavaScript?
Advertisements