数组表达式运算符主要用于文档中数组的操作,接上一篇:
MongoDB 聚合管道中使用数组表达式运算符($concatArrays合并数组)https://blog.csdn.net/m1729339749/article/details/130162048本篇我们主要介绍数组表达式运算符中用于断言数组的操作,断言数组的操作其目的是用于判断字段是否是数组,可以用于解决合并数组时我们可能会出现的问题,下面我们进行详细介绍:
一、语法
{ $isArray: <expression> }
判断是否是数组
二、准备工作
初始化成员数据
db.persons.insertMany([
{ "_id" : "1001", "name" : "张三", "fruits" : [ "apple", "pineapple" ], "toys": [ "橡皮鸭" ] },
{ "_id" : "1002", "name" : "李四", "fruits" : [ "banana", "apple" ] },
{ "_id" : "1003", "name" : "王五", "fruits" : null, "toys": [ "小卡车" ] },
{ "_id" : "1004", "name" : "赵六", "fruits" : [ ], "toys": [ "毛绒鹅" ] },
{ "_id" : "1005", "name" : "田七", "toys": [ "积木" ] },
])
三、示例
例子1:判断fruits、toys是否是数组
db.persons.aggregate([
{
$project: {
"name": 1,
"fruitsIsArray": { $isArray: "$fruits" },
"toysIsArray": { $isArray: "$toys" }
}
}
])
聚合查询的结果如下:
{ "_id" : "1001", "name" : "张三", "fruitsIsArray" : true, "toysIsArray" : true }
{ "_id" : "1002", "name" : "李四", "fruitsIsArray" : true, "toysIsArray" : false }
{ "_id" : "1003", "name" : "王五", "fruitsIsArray" : false, "toysIsArray" : true }
{ "_id" : "1004", "name" : "赵六", "fruitsIsArray" : true, "toysIsArray" : true }
{ "_id" : "1005", "name" : "田七", "fruitsIsArray" : false, "toysIsArray" : true }
从上面的结果可以看出,当字段不存在或者为null时,判断的结果为false
例子2:合并水果和玩具到喜欢的字段中
db.persons.aggregate([
{
$addFields: {
"favorite": {
$cond: {
if: { $isArray: "$fruits" },
then: "$fruits",
else: []
}
}
}
},
{
$addFields: {
"favorite": {
$cond: {
if: { $isArray: "$toys" },
then: { $concatArrays: [ "$favorite", "$toys" ] },
else: "$favorite"
}
}
}
}
])
聚合查询的结果如下:
{ "_id" : "1001", "name" : "张三", "fruits" : [ "apple", "pineapple" ], "toys" : [ "橡皮鸭" ], "favorite" : [ "apple", "pineapple", "橡皮鸭" ] }
{ "_id" : "1002", "name" : "李四", "fruits" : [ "banana", "apple" ], "favorite" : [ "banana", "apple" ] }
{ "_id" : "1003", "name" : "王五", "fruits" : null, "toys" : [ "小卡车" ], "favorite" : [ "小卡车" ] }
{ "_id" : "1004", "name" : "赵六", "fruits" : [ ], "toys" : [ "毛绒鹅" ], "favorite" : [ "毛绒鹅" ] }
{ "_id" : "1005", "name" : "田七", "toys" : [ "积木" ], "favorite" : [ "积木" ] }
通过上面的例子,我们成功解决了多个数组合并可能会出现的问题。