How to store MongoDB result in an array?


To store MongoDB result in an array, use the toArray() method −

var anyVariableName=db.yourCollectionName.find().toArray();

Let us first create a collection with documents −

> db.mongoDbResultInArrayDemo.insertOne({"CustomerName":"David Miller","CustomerAge":24,"isMarried":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd99bd5b50a6c6dd317ad92")
}
> db.mongoDbResultInArrayDemo.insertOne({"CustomerName":"Sam Williams","CustomerAge":46,"isMarried":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd99beab50a6c6dd317ad93")
}
> db.mongoDbResultInArrayDemo.insertOne({"CustomerName":"Carol Taylor","CustomerAge":23,"isMarried":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd99bf9b50a6c6dd317ad94")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.mongoDbResultInArrayDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd99bd5b50a6c6dd317ad92"),
   "CustomerName" : "David Miller",
   "CustomerAge" : 24,
   "isMarried" : false
}
{
   "_id" : ObjectId("5cd99beab50a6c6dd317ad93"),
   "CustomerName" : "Sam Williams",
   "CustomerAge" : 46,
   "isMarried" : true
}
{
   "_id" : ObjectId("5cd99bf9b50a6c6dd317ad94"),
   "CustomerName" : "Carol Taylor",
   "CustomerAge" : 23,
   "isMarried" : false
}

Following is the query to store MongoDB result in an array −

> var mongoDbResultIntoArray=db.mongoDbResultInArrayDemo.find().toArray();

Let us display the records of above variable −

> mongoDbResultIntoArray

This will produce the following output −

[
   {
      "_id" : ObjectId("5cd99bd5b50a6c6dd317ad92"),
      "CustomerName" : "David Miller",
      "CustomerAge" : 24,
      "isMarried" : false
   },
   {
      "_id" : ObjectId("5cd99beab50a6c6dd317ad93"),
      "CustomerName" : "Sam Williams",
      "CustomerAge" : 46,
      "isMarried" : true
   },
   {
      "_id" : ObjectId("5cd99bf9b50a6c6dd317ad94"),
      "CustomerName" : "Carol Taylor",
      "CustomerAge" : 23,
      "isMarried" : false
   }
]

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements