$sizeThe$sizeoperator matches any array with the number of elements specified by the argument.$size运算符将任何数组与参数指定的元素数匹配。
Compatibility兼容性
You can use 您可以将$size for deployments hosted in the following environments:$size用于在以下环境中托管的部署:
- MongoDB Atlas
: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
- MongoDB Enterprise
: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本 - MongoDB Community
: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本
Consider the following examples:考虑以下示例:
db.collection.find( { field: { $size: 2 } } );
This query 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 要匹配数组中只有一个元素的字段,请使用值为1的$size with a value of 1, as follows:$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部分使用索引,但查询的其他部分可以在适用的情况下使用索引。
Syntax语法
A $size expression has the following syntax:$size表达式具有以下语法:
{
<field>: {
$size: <number>
}
}Additional Examples其他示例
For additional examples on querying arrays, see:有关查询数组的其他示例,请参阅:
For additional examples on querying, see Query Documents.有关查询的其他示例,请参阅查询文档。