13

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
  • 13,141
  • 42
  • 113
  • 200

1 Answers1

32

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

kuzey beytar
  • 3,076
  • 6
  • 37
  • 46
Chris Heald
  • 61,439
  • 10
  • 123
  • 137
  • 7
    For the full query: `db.getCollection('col').updateOne({}, {$push: {"field": {$each: ["val1"], $slice: -10}}})` – Steinfeld Apr 05 '19 at 09:07