MongoDB聚合运算符:$size

MongoDB聚合运算符:$size


$size聚合运算符返回数组中元素的数量。

语法

{ $size: <expression> }

<expression>为可解析为数组的表达式。

使用

$size 的参数必须解析为数组。如果 $size 的参数丢失或不能析为数组,则 $size 错误。

举例

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" }

下面的聚合操作使用 $size 运算符返回color数组中的元素数量:

db.inventory.aggregate([
   {
      $project: {
         item: 1,
         numberOfColors: { $cond: { if: { $isArray: "$colors" }, then: { $size: "$colors" }, else: "NA"} }
      }
   }
] )

操作返回下面的结果:

{ "_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" }

相关推荐

  1. MongoDB聚合运算符:$size

    2024-04-30 06:14:05       34 阅读
  2. MongoDB聚合运算符:$add

    2024-04-30 06:14:05       55 阅读
  3. MongoDB聚合运算符:$arrayToObject

    2024-04-30 06:14:05       52 阅读
  4. MongoDB聚合运算符;$dateToParts

    2024-04-30 06:14:05       53 阅读
  5. MongoDB聚合运算符:$dayOfWeek

    2024-04-30 06:14:05       54 阅读
  6. MongoDB聚合运算符:$dayOfMonth

    2024-04-30 06:14:05       51 阅读
  7. MongoDB聚合运算符;$dateToString

    2024-04-30 06:14:05       48 阅读
  8. MongoDB聚合运算符:$dayOfYear

    2024-04-30 06:14:05       48 阅读
  9. MongoDB聚合运算符:$denseRank

    2024-04-30 06:14:05       42 阅读
  10. MongoDB聚合运算符:$dateTrunc

    2024-04-30 06:14:05       45 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-30 06:14:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-30 06:14:05       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-30 06:14:05       82 阅读
  4. Python语言-面向对象

    2024-04-30 06:14:05       91 阅读

热门阅读

  1. Hadoop 伪分布式安装

    2024-04-30 06:14:05       38 阅读
  2. 云计算中的网络服务

    2024-04-30 06:14:05       35 阅读
  3. CentOS 常见的命令

    2024-04-30 06:14:05       37 阅读
  4. Circuits--Sequential--Finite6

    2024-04-30 06:14:05       32 阅读
  5. 记录一下初次使用linux服务器的问题解决

    2024-04-30 06:14:05       32 阅读
  6. Visual Studio 2019 远程调试工具

    2024-04-30 06:14:05       34 阅读
  7. MySQL 高级 - 第四章 | 配置文件与系统变量

    2024-04-30 06:14:05       24 阅读
  8. 清理 Conda 和 pip 缓存

    2024-04-30 06:14:05       28 阅读