数组表达式运算符主要用于文档中数组的操作,本篇我们主要介绍如何使用数组表达式运算符获取数组的长度以及对数组中的数据进行反转:
一、准备数据
初始化成员数据
db.persons.insertMany([
{ "_id" : "1001", "name" : "张三", "fruits" : [ "apple", "orange" ] },
{ "_id" : "1002", "name" : "李四", "fruits" : [ "banana", "apple" ] },
{ "_id" : "1003", "name" : "王五", "fruits" : [ "banana", "apple", "orange" ] },
{ "_id" : "1004", "name" : "赵六", "fruits" : [ ] },
{ "_id" : "1005", "name" : "田七" },
])
二、获取数组长度($size)
语法:{ $size: <expression> }
获取数组长度
例子:计算成员喜欢的水果数量
db.persons.aggregate([
{
$project: {
"name": 1,
"favoriteFruitQuantity": {
$size: "$fruits"
}
}
}
])
聚合查询的结果如下:
{
"ok" : 0,
"errmsg" : "The argument to $size must be an array, but was of type: missing",
"code" : 17124,
"codeName" : "Location17124"
}
发现报错了,原因是在编号为1005的成员中不存在fruits字段导致的。
这里我们需要使用$isArray断言数组操作进行聚合查询,如果您对$isArray断言数组操作不太了解,可以参考:
MongoDB 聚合管道中使用数组表达式运算符断言数组($isArray)https://blog.csdn.net/m1729339749/article/details/130162535
下面我们使用$isArray断言数组操作改进聚合查询:
db.persons.aggregate([
{
$project: {
"name": 1,
"favoriteFruitQuantity": {
$cond: {
if: { $isArray: "$fruits" },
then: { $size: "$fruits" },
else: 0
}
}
}
}
])
聚合查询的结果如下:
{ "_id" : "1001", "name" : "张三", "favoriteFruitQuantity" : 2 }
{ "_id" : "1002", "name" : "李四", "favoriteFruitQuantity" : 2 }
{ "_id" : "1003", "name" : "王五", "favoriteFruitQuantity" : 3 }
{ "_id" : "1004", "name" : "赵六", "favoriteFruitQuantity" : 0 }
{ "_id" : "1005", "name" : "田七", "favoriteFruitQuantity" : 0 }
三、反转数组($reverseArray)
语法:{ $reverseArray: <array expression> }
对数组中的数据进行反转
例子:反转喜欢的水果顺序
db.persons.aggregate([
{
$project: {
"name": 1,
"reverseFruits": { $reverseArray: "$fruits" }
}
}
])
聚合查询的结果如下:
{ "_id" : "1001", "name" : "张三", "reverseFruits" : [ "orange", "apple" ] }
{ "_id" : "1002", "name" : "李四", "reverseFruits" : [ "apple", "banana" ] }
{ "_id" : "1003", "name" : "王五", "reverseFruits" : [ "orange", "apple", "banana" ] }
{ "_id" : "1004", "name" : "赵六", "reverseFruits" : [ ] }
{ "_id" : "1005", "name" : "田七", "reverseFruits" : null }