Fetch specific documents with array values in MongoD

To fetch specific documents with array values in MongoDB, use the limit() method combined with toArray(). The toArray() method returns an array containing all documents from a cursor, while limit() restricts the number of documents returned.

Syntax

db.collection.find().limit(numberOfDocuments).toArray()

Create Sample Data

Let us create a collection with documents containing array values ?

db.demo482.insertMany([
    {_id:1, "StudentInformation":[{"Name":"Chris","Age":21}]},
    {_id:2, "StudentInformation":[{"Name":"Bob","Age":23}]},
    {_id:3, "StudentInformation":[{"Name":"David","Age":20}]}
]);
{
    "acknowledged" : true,
    "insertedIds" : [ 1, 2, 3 ]
}

Display All Documents

db.demo482.find();
{ "_id" : 1, "StudentInformation" : [ { "Name" : "Chris", "Age" : 21 } ] }
{ "_id" : 2, "StudentInformation" : [ { "Name" : "Bob", "Age" : 23 } ] }
{ "_id" : 3, "StudentInformation" : [ { "Name" : "David", "Age" : 20 } ] }

Example: Fetch Specific Documents with limit()

Following query fetches the first 2 documents as an array ?

db.demo482.find({}).limit(2).toArray();
[
    {
        "_id" : 1,
        "StudentInformation" : [
            {
                "Name" : "Chris",
                "Age" : 21
            }
        ]
    },
    {
        "_id" : 2,
        "StudentInformation" : [
            {
                "Name" : "Bob",
                "Age" : 23
            }
        ]
    }
]

Key Points

  • limit() restricts the number of documents returned from the query
  • toArray() converts the cursor result into a JavaScript array format
  • Useful for pagination and controlling result set size

Conclusion

The limit() and toArray() combination provides an efficient way to fetch a specific number of documents with array values. This approach is particularly useful for pagination and memory management in large collections.

Updated on: 2026-03-15T03:07:43+05:30

146 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements