Get a single element from the array of results by index in MongoDB

To get a single element from an array of results by index in MongoDB, use the aggregation framework with $skip and $limit operators. The $skip operator skips a specified number of documents, while $limit restricts the output to one document.

Syntax

db.collection.aggregate([
    { $match: { "field": "value" } },
    { $skip: index },
    { $limit: 1 }
]);

Sample Data

Let us first create a collection with documents −

db.demo391.insertMany([
    { "_id": 101, "Name": "Chris", "Values": ["101", "102"] },
    { "_id": 111, "Name": "Chris", "Values": ["101", "102"] },
    { "_id": 121, "Name": "Chris", "Values": ["101", "102"] }
]);
{
    "acknowledged": true,
    "insertedIds": [101, 111, 121]
}

Display all documents from the collection −

db.demo391.find();
{ "_id": 101, "Name": "Chris", "Values": ["101", "102"] }
{ "_id": 111, "Name": "Chris", "Values": ["101", "102"] }
{ "_id": 121, "Name": "Chris", "Values": ["101", "102"] }

Example: Get Element at Index 2

To get the element at index 2 (3rd document) from the results −

var i = 2;
db.demo391.aggregate([
    { $match: { "Name": "Chris" } },
    { $skip: i - 1 },
    { $limit: 1 }
]);
{ "_id": 111, "Name": "Chris", "Values": ["101", "102"] }

How It Works

  • $match filters documents based on the specified criteria
  • $skip skips the first (i-1) documents from the matched results
  • $limit returns only one document from the remaining results

Conclusion

Use the aggregation pipeline with $skip and $limit to retrieve a specific document by its position in the result set. This approach is useful when you need to paginate results or access documents at specific indices.

Updated on: 2026-03-15T02:47:09+05:30

591 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements