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: 2020-05-11T09:22:47+05:30

922 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements