How to push an array in MongoDB?


To push an array, use $push in MongoDB. Let us first create a collection with documents −

> db.demo399.insertOne({Name:"Chris",Age:21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e610339fac4d418a017856d")
}
> db.demo399.insertOne({Name:"David",Age:22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e610341fac4d418a017856e")
}
> db.demo399.insertOne({Name:"Chris",Age:21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e610355fac4d418a017856f")
}
> db.demo399.insertOne({Name:"Bob",Age:23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e61035efac4d418a0178570")
}
> db.demo399.insertOne({Name:"David",Age:22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e610364fac4d418a0178571")
}

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

> db.demo399.find();

This will produce the following output −

{ "_id" : ObjectId("5e610339fac4d418a017856d"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e610341fac4d418a017856e"), "Name" : "David", "Age" : 22 }
{ "_id" : ObjectId("5e610355fac4d418a017856f"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e61035efac4d418a0178570"), "Name" : "Bob", "Age" : 23 }
{ "_id" : ObjectId("5e610364fac4d418a0178571"), "Name" : "David", "Age" : 22 }

Following is the query to push an array −

> db.demo399.aggregate(
...    [
...       {
...          $group:
...          {
...             _id: null,
...             array: { $push: { Name: "$Name", Age: "$Age" } }
...          }
...       }
...    ]
... )

This will produce the following output −

{ "_id" : null, "array" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 22 }, { "Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 23 }, { "Name" : "David", "Age" : 22 } ] }

Updated on: 03-Apr-2020

377 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements