Query an array in MongoDB to fetch a specific value


To fetch a specific value from an array, use aggregate() along with $project. Let us create a collection with documents −

> db.demo761.insertOne(
...    {
...       "details": [
...          {
...             "student": {
...                "FullName": "Chris Brown"
...             }
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb034d15637cd592b2a4af1")
}
> db.demo761.insertOne(
...    {
...       "details": [
...          {
...             "student": {
...                "FullName": "Chris Taylor"
...             }
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb034d25637cd592b2a4af2")
}

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

> db.demo761.find();

This will produce the following output −

{ "_id" : ObjectId("5eb034d15637cd592b2a4af1"), "details" : [ { "student" : { "FullName" : "Chris Brown" } } ] }
{ "_id" : ObjectId("5eb034d25637cd592b2a4af2"), "details" : [ { "student" : { "FullName" : "Chris Taylor" } } ] }

Following is how to query an array in MongoDB −

> db.demo761.aggregate([
...    {'$unwind':'$details'},
...    {'$match': {
...       'details.student.FullName':'Chris Taylor',
...    }},
...    {'$project': {
...       'details.student.FullName': 1, '_id': 0
...    }},
... ])

This will produce the following output −

{ "details" : { "student" : { "FullName" : "Chris Taylor" } } }

Updated on: 01-Jul-2020

490 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements