On this page本页内容
$size
Counts and returns the total number of items in an array.计算并返回数组中的项目总数。
$size
has the following syntax:语法如下:
{ $size: <expression> }
The argument for $size
can be any expression as long as it resolves to an array. $size
的参数可以是任何表达式,只要它解析为数组即可。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
The argument for $size
must resolve to an array. $size
的参数必须解析为数组。If the argument for 如果$size
is missing or does not resolve to an array, $size
errors.$size
的参数丢失或无法解析为数组,则$size
错误。
Consider an 考虑使用以下文档进行inventory
collection with the following documents:inventory
集合:
{ "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] } { "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "purple" ] } { "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ ] } { "_id" : 4, "item" : "ZZZ1", "description" : "product 4 - missing colors" } { "_id" : 5, "item" : "ZZZ2", "description" : "product 5 - colors is string", colors: "blue,red" }
The following aggregation pipeline operation uses the 以下聚合管道操作使用$size
operator to return the number of elements in the colors
array:$size
运算符返回colors
数组中的元素数:
db.inventory.aggregate([ { $project: { item: 1, numberOfColors: { $cond: { if: { $isArray: "$colors" }, then: { $size: "$colors" }, else: "NA"} } } } ] )
The operation returns the following:运算结果如下:
{ "_id" : 1, "item" : "ABC1", "numberOfColors" : 3 } { "_id" : 2, "item" : "ABC2", "numberOfColors" : 1 } { "_id" : 3, "item" : "XYZ1", "numberOfColors" : 0 } { "_id" : 4, "item" : "ZZZ1", "numberOfColors" : "NA" } { "_id" : 5, "item" : "ZZZ2", "numberOfColors" : "NA" }