$size

On this page本页内容

$size

The $size operator matches any array with the number of elements specified by the argument. $size运算符将任何数组与参数指定的元素数相匹配。For example:例如:

db.collection.find( { field: { $size: 2 } } );

returns all documents in collection where field is an array with 2 elements. 返回collection中的所有其中field是包含2个元素的数组的文档。For instance, the above expression will return { field: [ red, green ] } and { field: [ apple, lime ] } but not { field: fruit } or { field: [ orange, lemon, grapefruit ] }. 例如,上面的表达式将返回{ field: [ red, green ] }{ field: [ apple, lime ] }但不返回{ field: fruit }也不返回{ field: [ orange, lemon, grapefruit ] }To match fields with only one element within an array use $size with a value of 1, as follows:要匹配数组中只有一个元素的字段,请使用值为1的$size,如下所示:

db.collection.find( { field: { $size: 1 } } );

$size does not accept ranges of values. 不接受值的范围。To select documents based on fields with different numbers of elements, create a counter field that you increment when you add elements to a field.要根据具有不同元素数的字段选择文档,请创建计数器字段,在向字段添加元素时,该字段将递增。

Queries cannot use indexes for the $size portion of a query, although the other portions of a query can use indexes if applicable.查询不能为查询的$size部分使用索引,尽管查询的其他部分可以使用索引(如果适用)。

Additional Examples其他示例

For additional examples in querying arrays, see:有关查询数组的其他示例,请参阅:

For additional examples in querying, see:有关查询中的其他示例,请参阅:

See also参阅

db.collection.find()