Search code examples
arraysmongodblimit

How to limit an array size in MongoDB?


is there a way I can limit the number of elements that can be added to a MongoDB Array? I have a Tables collection with an Attendees array that should only contain 10 elements seats).

Thank you!


Solution

  • You can use $slice as a modifier to $push when you update the document:

    $push: { "field": { $each: ["val1", "val2"], $slice: -10 }}
    

    This will cause field to only consist of the last 10 elements (giving you a "rolling window" of values pushed into the field).