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
Getting only the first item for an array property in MongoDB?
To get only the first item from an array property in MongoDB, use the $slice operator in the projection stage. This operator limits the number of array elements returned in the query result.
Syntax
db.collection.find(
{ query },
{ arrayField: { $slice: 1 } }
);
Sample Data
db.gettingFirstItemInArrayDemo.insertOne({
"UserId": 101,
"UserName": "Carol",
"UserOtherDetails": [
{"UserFriendName": "Sam"},
{"UserFriendName": "Mike"},
{"UserFriendName": "David"},
{"UserFriendName": "Bob"}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cdfca52bf3115999ed51205")
}
Example: Get First Array Element
To retrieve only the first element from the UserOtherDetails array ?
db.gettingFirstItemInArrayDemo.find(
{"UserId": 101},
{UserOtherDetails: {$slice: 1}}
);
{
"_id": ObjectId("5cdfca52bf3115999ed51205"),
"UserId": 101,
"UserName": "Carol",
"UserOtherDetails": [
{"UserFriendName": "Sam"}
]
}
Key Points
-
$slice: 1returns only the first element of the array -
$slice: -1would return only the last element - The
$sliceoperator works in the projection stage, not the query stage
Conclusion
The $slice operator effectively limits array elements in MongoDB query results. Use $slice: 1 in the projection to retrieve only the first item from any array property.
Advertisements
