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" ] }

Updated on: 02-Apr-2020

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements