How to get only values in arrays with MongoDB aggregate?


Let us create a collection with documents −

> db.demo411.insertOne(
...    {
...       "Information" : [
...          {
...             "Name1" : "Chris",
...             "Name2" : "David"
...          },
...          {
...             "Name1" : "John",
...             "Name2" : "John"
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70f19715dc524f70227682")
}

Display all documents from a collection with the help of find() method −

> db.demo411.find();

This will produce the following output −

{ "_id" : ObjectId("5e70f19715dc524f70227682"), "Information" : [ { "Name1" : "Chris", "Name2" : "David" }, { "Name1" : "John", "Name2" : "John" } ] }

Following is the query to get only values in arrays −

> db.demo411.aggregate(
...    [
...       {$project : {
...          _id : 0,
...          Information : {$map : {input : "$Information", as : "out", in : ["$$out.Name1", "$$out.Name2"]}}
...          }
...       }
...    ]
... )

This will produce the following output −

{ "Information" : [ [ "Chris", "David" ], [ "John", "John" ] ] }

Updated on: 03-Apr-2020

767 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements