How to store MongoDB result in an array?

To store MongoDB result in an array, use the toArray() method. This converts the cursor returned by MongoDB queries into a JavaScript array that can be manipulated and accessed using array methods.

Syntax

var arrayVariable = db.collectionName.find().toArray();

Create Sample Data

Let us first create a collection with documents ?

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

Display All Documents

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

db.mongoDbResultInArrayDemo.find().pretty();
{
    "_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
}

Store Result in Array

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
[
    {
        "_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
    }
]

Conclusion

The toArray() method converts MongoDB cursor results into a JavaScript array format. This enables you to use standard array methods and makes the data easier to manipulate in your applications.

Updated on: 2026-03-15T01:21:50+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements