MongoDB aggregation to fetch documents with specific field value?


For this, use aggregate(). Let’s say we have to fetch documents with a field “Age” with value “21”.

Let us now create a collection with documents −

> db.demo685.insertOne(
...    {
...       "details":
...       [
...          {
...             Name:"Chris",
...             Age:21
...          },
...          {
...             Name:"David",
...             Age:23
...          },
...          {
...             Name:"Bob",
...             Age:21
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea54f6fa7e81adc6a0b395b")
}

Display all documents from a collection with the help of find() method −

> db.demo685.find();

This will produce the following output −

{ "_id" : ObjectId("5ea54f6fa7e81adc6a0b395b"), "details" : [
   { "Name" : "Chris", "Age" : 21 },
   { "Name" : "David", "Age" : 23 },
   { "Name" : "Bob", "Age" : 21 } 
] }

Following is the query for MongoDB aggregation −

> db.demo685.aggregate([ { $unwind: "$details" }, { $match: { "details.Age": 21 } }, { $project: {_id: 0}} ]).pretty();

This will produce the following output −

{ "details" : { "Name" : "Chris", "Age" : 21 } }
{ "details" : { "Name" : "Bob", "Age" : 21 } }

Updated on: 14-May-2020

532 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements