How to get items from an object array in MongoDB?


To get items from an object array, use aggregate(). Let us create a collection with documents −

> db.demo459.insertOne(
... { "_id" : 1,
... "Information" : [
...    {
...       "Name" : "Chris",
...       "_id" : new ObjectId(),
...       "details" : [
...          "HR"
...       ]
...    },
... {
...
...    "Name" : "David",
...    "_id" : new ObjectId(),
...    "details" : [
...       "Developer"
...    ]
... },
... {
...
...    "Name" : "Bob",
...    "_id" : new ObjectId(),
...    "details" : [
...       "Account"
...    ]
... }
... ]
... }
... )
{ "acknowledged" : true, "insertedId" : 1 }

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

> db.demo459.find();

This will produce the following output −

{ "_id" : 1, "Information" : [ { "Name" : "Chris", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95c9"),
"details" : [ "HR" ] }, { "Name" : "David", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95ca"),
"details" : [ "Developer" ] }, { "Name" : "Bob", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95cb"),
"details" : [ "Account" ] } ] }

Following is the query to get items from an object array in MongoDB −

> db.demo459.aggregate([
...    { $unwind: '$Information' },
...    { $unwind: '$Information.details' },
...    { $match: { 'Information.Name': { $in: ["Chris","Bob"]} } },
...    { $group: { _id: null, detailList: { $addToSet: '$Information.details' } } },
... ])

This will produce the following output −

{ "_id" : null, "detailList" : [ "Account", "HR" ] }

Updated on: 11-May-2020

733 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements