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
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" } ] }Advertisements