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!

1 Answer 1

35

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

Sign up to request clarification or add additional context in comments.

1 Comment

For the full query: db.getCollection('col').updateOne({}, {$push: {"field": {$each: ["val1"], $slice: -10}}})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.