Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to get array from a MongoDB collection?
You can use aggregate framework. Let us first create a collection with documents −
> db.getArrayDemo.insertOne(
{
"CustomerId":101,
"CustomerDetails":[
{
"CustomerName":"Larry",
"CustomerFriendDetails":[
{
"CustomerFriendName":"Sam"
},
{
"CustomerFriendName":"Robert"
}
]
},
{
"CustomerName":"Chris",
"CustomerFriendDetails":[
{
"CustomerFriendName":"David"
},
{
"CustomerFriendName":"Carol"
}
]
}
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cda4949b50a6c6dd317adb7")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.getArrayDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cda4949b50a6c6dd317adb7"),
"CustomerId" : 101,
"CustomerDetails" : [
{
"CustomerName" : "Larry",
"CustomerFriendDetails" : [
{
"CustomerFriendName" : "Sam"
},
{
"CustomerFriendName" : "Robert"
}
]
},
{
"CustomerName" : "Chris",
"CustomerFriendDetails" : [
{
"CustomerFriendName" : "David"
},
{
"CustomerFriendName" : "Carol"
}
]
}
]
}
Following is the query to get array from MongoDB collection −
> db.getArrayDemo.aggregate([
{ "$unwind": "$CustomerDetails" },
{ "$unwind": "$CustomerDetails.CustomerFriendDetails"},
{
"$group": {
"_id": null,
"CustomerFriendDetails": { "$push": "$CustomerDetails.CustomerFriendDetails.CustomerFriendName" }
}
}
]);
This will produce the following output −
{ "_id" : null, "CustomerFriendDetails" : [ "Sam", "Robert", "David", "Carol" ] } Advertisements
