Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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