Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
$matchfilters documents based on the specified criteria -
$skipskips the first (i-1) documents from the matched results -
$limitreturns 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.
Advertisements
