Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 521
Trung Tran Avatar asked Apr 29 '15 01:04

Trung Tran


Video Answer


1 Answers

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

like image 187
Chris Heald Avatar answered Sep 28 '22 03:09

Chris Heald