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
Extract all the values and display in a single line with MongoDB
Let us first create a collection with documents −
> db.demo389.insertOne(
... {
... "details":[
... {
... "Name":[
... "Chris",
... "David"
... ]
... },
... {
... "Name":[
... "Bob",
... "Mike"
... ]
... },
... {
... "Name":[
... "Carol",
... "Sam"
... ]
... },
... {
... "Name":[
... "David",
... "John"
... ]
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5d1d8f22064be7ab44e7f9")
}
Display all documents from a collection with the help of find() method −
> db.demo389.find();
This will produce the following output −
{
"_id" : ObjectId("5e5d1d8f22064be7ab44e7f9"), "details" : [
{ "Name" : [ "Chris", "David" ] }, { "Name" : [ "Bob", "Mike" ] },
{ "Name" : [ "Carol", "Sam" ] }, { "Name" : [ "David", "John" ] }
]
}
Following is the query to extract all the values −
> db.demo389.aggregate([
... {
... $unwind: "$details"
... },
... {
... $unwind: "$details.Name"
... },
... {
... $project: {
... "_id": "$_id",
... "Name": "$details.Name"
... }
... },
... {
... $group: {
... _id: "_id",
... out: {
... $push: "$Name"
... }
... }
... },
... {
... $project: {
... "_id": 0,
... "NameArray": "$out"
... }
... }
... ])
This will produce the following output −
{ "NameArray" : [ "Chris", "David", "Bob", "Mike", "Carol", "Sam", "David", "John" ] }Advertisements