Can we search an array of objects in MongoDB?


Yes, to search an array of objects, use $unwind in MongoDB aggregate(). To match, use $match. Let us create a collection with documents −

> db.demo623.insertOne(
...    {
...       _id:1,
...       details:[
...          {
...             Name:"Chris"
...          },
...          {
...             DueDate:new ISODate("2020-01-10")
...          },
...          {
...             CountryName:"US"
...          }
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 1 }

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

> db.demo623.find().pretty();

This will produce the following output −

{
   "_id" : 1,
   "details" : [
      {
         "Name" : "Chris"
      },
      {
         "DueDate" : ISODate("2020-01-10T00:00:00Z")
      },
      {
         "CountryName" : "US"
      }
   ]
}

Following is the query to search an array of objects in MongoDB −

> db.demo623.aggregate({$unwind: "$details"},
... {$match: {"details.Name":"Chris"}},
... {$project: {"details.Name": 1}})

This will produce the following output −

{ "_id" : 1, "details" : { "Name" : "Chris" } }

Updated on: 12-May-2020

365 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements