$size (aggregation)
On this page本页内容
Definition定义
$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. For more information on expressions, see Expressions.$size
的参数可以是任何表达式,只要它解析为数组即可。有关表达式的详细信息,请参阅表达式。
Behavior行为
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
将出错。
Example实例
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" }