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

Updated on: 13-May-2020

898 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements