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
How to get a particular element from MongoDB array?
To get a particular element from a MongoDB array, use the $arrayElemAt operator within the aggregation framework. This operator allows you to extract an element at a specific index position from an array field.
Syntax
db.collection.aggregate([
{
$project: {
fieldName: { $arrayElemAt: ["$arrayField", index] }
}
}
]);
Sample Data
db.getParticularElement.insertOne({
"InstructorName": "Larry",
"InstructorTechnicalSubject": ["Java", "C", "C++", "MongoDB", "MySQL", "SQL Server"]
});
{
"acknowledged": true,
"insertedId": ObjectId("5c7ee027559dd2396bcfbfb1")
}
Display all documents from the collection ?
db.getParticularElement.find().pretty();
{
"_id": ObjectId("5c7ee027559dd2396bcfbfb1"),
"InstructorName": "Larry",
"InstructorTechnicalSubject": [
"Java",
"C",
"C++",
"MongoDB",
"MySQL",
"SQL Server"
]
}
Example: Get Element at Index 3
Extract the 4th element (index 3) from the InstructorTechnicalSubject array ?
db.getParticularElement.aggregate([
{
$project: {
FourthElement: { $arrayElemAt: ["$InstructorTechnicalSubject", 3] }
}
}
]);
{ "_id": ObjectId("5c7ee027559dd2396bcfbfb1"), "FourthElement": "MongoDB" }
Key Points
- Array indexing starts from 0, so index 3 represents the 4th element.
- Use negative indices to access elements from the end:
-1for last element. - Returns
nullif the index is out of bounds.
Conclusion
The $arrayElemAt operator provides a simple way to extract specific array elements by index position. Use it within aggregation pipelines to project individual array elements as separate fields.
Advertisements
