Create array with MongoDB query?

You can use the toArray() method with MongoDB queries to convert query results into an array format. This method transforms the cursor returned by find() into a JavaScript array containing all matching documents.

Syntax

db.collectionName.find({}, {fieldName: 1}).toArray();

Sample Data

Let us create a collection with sample documents ?

db.createArrayDemo.insertMany([
    {"UserName": "Chris"},
    {"UserName": "David"},
    {"UserName": "Robert"},
    {"UserName": "Sam"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cbd6461de8cc557214c0e00"),
        ObjectId("5cbd6467de8cc557214c0e01"),
        ObjectId("5cbd646cde8cc557214c0e02"),
        ObjectId("5cbd6470de8cc557214c0e03")
    ]
}

Display all documents from the collection ?

db.createArrayDemo.find();
{ "_id": ObjectId("5cbd6461de8cc557214c0e00"), "UserName": "Chris" }
{ "_id": ObjectId("5cbd6467de8cc557214c0e01"), "UserName": "David" }
{ "_id": ObjectId("5cbd646cde8cc557214c0e02"), "UserName": "Robert" }
{ "_id": ObjectId("5cbd6470de8cc557214c0e03"), "UserName": "Sam" }

Case 1: Create Array Without _id Field

To create an array of UserName field values without the _id field ?

db.createArrayDemo.find({}, {_id: 0, UserName: 1}).toArray();
[
    {
        "UserName": "Chris"
    },
    {
        "UserName": "David"
    },
    {
        "UserName": "Robert"
    },
    {
        "UserName": "Sam"
    }
]

Case 2: Create Array With Only _id Field

To create an array containing only the _id field values ?

db.createArrayDemo.find({}, {_id: 1}).toArray();
[
    {
        "_id": ObjectId("5cbd6461de8cc557214c0e00")
    },
    {
        "_id": ObjectId("5cbd6467de8cc557214c0e01")
    },
    {
        "_id": ObjectId("5cbd646cde8cc557214c0e02")
    },
    {
        "_id": ObjectId("5cbd6470de8cc557214c0e03")
    }
]

Key Points

  • Use projection {fieldName: 1} to include specific fields in the array.
  • Use {_id: 0} to exclude the _id field from results.
  • The toArray() method converts the cursor to a JavaScript array format.

Conclusion

The toArray() method efficiently converts MongoDB query results into arrays. Combine it with field projection to create arrays containing only the specific fields you need for your application.

Updated on: 2026-03-15T00:50:41+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements