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 for capped sub-collection in an array
In MongoDB, you cannot create capped sub-collections within arrays. However, you can limit the number of array elements returned using the $slice operator in aggregation pipelines to achieve similar functionality.
Syntax
db.collection.aggregate([
{ $project: { fieldName: { $slice: [ "$arrayField", numberOfElements ] } } }
]);
Sample Data
db.demo319.insertMany([
{"Scores": [100, 345, 980, 890]},
{"Scores": [903, 10004, 84575, 844]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e50ecf6f8647eb59e562064"),
ObjectId("5e50ed01f8647eb59e562065")
]
}
Display All Documents
db.demo319.find().pretty();
{
"_id": ObjectId("5e50ecf6f8647eb59e562064"),
"Scores": [
100,
345,
980,
890
]
}
{
"_id": ObjectId("5e50ed01f8647eb59e562065"),
"Scores": [
903,
10004,
84575,
844
]
}
Example: Limit Array Elements Using $slice
To return only the first 2 elements from each Scores array ?
db.demo319.aggregate([
{ $project: {TwoScores: { $slice: [ "$Scores", 2 ] } } }
]);
{ "_id": ObjectId("5e50ecf6f8647eb59e562064"), "TwoScores": [ 100, 345 ] }
{ "_id": ObjectId("5e50ed01f8647eb59e562065"), "TwoScores": [ 903, 10004 ] }
Key Points
- MongoDB does not support capped sub-collections within document arrays
-
$sliceoperator limits array elements in query results without modifying stored data - Use positive numbers to get elements from the beginning of the array
Conclusion
While MongoDB doesn't support capped sub-collections in arrays, the $slice operator provides effective array element limiting in aggregation pipelines. This approach gives you control over the number of array elements returned in query results.
Advertisements
