 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" ] }Advertisements
 