如何限制MongoDB中的数组大小? [英] How to limit an array size in MongoDB?
本文介绍了如何限制MongoDB中的数组大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以限制可以添加到MongoDB数组中的元素的数量?我有一个Tables
集合和一个Attendees
数组,该数组只能包含10个元素.)
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).
谢谢!
推荐答案
您可以使用 $ slice 作为更新文档时对$push
的修饰符:
You can use $slice as a modifier to $push
when you update the document:
$push: {"field": $each: ["val1", "val2"], $slice: -10}
这将导致field
仅由最后10个元素组成(为您提供了一个滚动窗口",其中的值被推入字段).
This will cause field
to only consist of the last 10 elements (giving you a "rolling window" of values pushed into the field).
这篇关于如何限制MongoDB中的数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文