7

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!

Trung Tran
  • 11,579
  • 39
  • 105
  • 187

1 Answers1

23

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).

Chris Heald
  • 59,258
  • 10
  • 117
  • 133
  • 4
    For the full query: `db.getCollection('col').updateOne({}, {$push: {"field": {$each: ["val1"], $slice: -10}}})` – Steinfeld Apr 05 '19 at 09:07