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
  • $slice operator 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.

Updated on: 2026-03-15T02:29:27+05:30

464 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements