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
MongoDB query to limit the returning values of a field?
To limit the returning values of a field in MongoDB, use the $slice operator in the projection parameter of the find() method. This is particularly useful for limiting array elements returned in query results.
Syntax
db.collection.find(
{},
{ "arrayField": { "$slice": numberOfElements } }
);
Sample Data
db.demo594.insertOne({
id: 1,
details: [
{ Name: "Chris", Age: 21 },
{ Name: "Bob", Age: 20 },
{ Name: "David", Age: 23 },
{ Name: "Sam", Age: 22 }
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e933459fd2d90c177b5bcdd")
}
View All Documents
db.demo594.find();
{
"_id": ObjectId("5e933459fd2d90c177b5bcdd"),
"id": 1,
"details": [
{ "Name": "Chris", "Age": 21 },
{ "Name": "Bob", "Age": 20 },
{ "Name": "David", "Age": 23 },
{ "Name": "Sam", "Age": 22 }
]
}
Example: Limit Array Elements
To return only the first element from the details array ?
db.demo594.find({}, { "details": { "$slice": 1 } });
{
"_id": ObjectId("5e933459fd2d90c177b5bcdd"),
"id": 1,
"details": [
{ "Name": "Chris", "Age": 21 }
]
}
Key Points
-
$sliceworks only with array fields in the projection stage. - Use positive numbers to get elements from the beginning, negative numbers from the end.
- You can combine
$slicewith other projection operators to include/exclude specific fields.
Conclusion
The $slice operator effectively limits array field values in MongoDB query results. Use it in the projection parameter to control how many array elements are returned, optimizing query performance and reducing data transfer.
Advertisements
