数组表达式运算符主要用于文档中数组的操作,本篇我们主要介绍数组表达式运算符中用于过滤数组的操作,下面我们进行详细介绍:
一、语法
{
$filter:
{
input: <array>,
cond: <expression>,
as: <string>,
limit: <number expression>
}
}
其中,
input:代表的是数组
cond:代表的是条件
as:可选,定义的变量,用于接收数组中的当前元素,如果未定义在cond表达式中可以使用$$this获取数组中的当前元素
limit:可选,限制数组中元素的个数
二、准备工作
初始化零食数据
db.goods.insertMany([
{ "_id" : 1, "name" : "薯片", "types" : [
{ "size" : "S", "quantity" : 10, "price" : 8 },
{ "size" : "L", "quantity" : 8, "price" : 12 }
]},
{ "_id" : 2, "name" : "牛肉干", "types" : [
{ "size" : "L", "quantity" : 5, "price" : 30}
]},
{ "_id" : 3, "name" : "可口可乐", "types" : [
{ "size" : "S", "quantity" : 10, "price" : 3 },
{ "size" : "L", "quantity" : 6, "price" : 10 }
]},
{ "_id" : 4, "name" : "旺仔牛奶", "types" : [
{ "size" : "L", "quantity" : 10, "price" : 5 }
]}
])
三、示例
例子1:只查看型号为L的型号信息
db.goods.aggregate([
{
$project: {
types: {
$filter: {
input: "$types",
cond: { $eq: [ "$$this.size", "L" ] }
}
}
}
}
])
等效于:
db.goods.aggregate([
{
$project: {
types: {
$filter: {
input: "$types",
as: "type",
cond: { $eq: [ "$$type.size", "L" ] }
}
}
}
}
])
聚合查询的结果如下:
{ "_id" : 1, "types" : [ { "size" : "L", "quantity" : 8, "price" : 12 } ] }
{ "_id" : 2, "types" : [ { "size" : "L", "quantity" : 5, "price" : 30 } ] }
{ "_id" : 3, "types" : [ { "size" : "L", "quantity" : 6, "price" : 10 } ] }
{ "_id" : 4, "types" : [ { "size" : "L", "quantity" : 10, "price" : 5 } ] }
as用于定义一个存储数组中当前元素的变量,使用变量时前面需要加上 "$$";
如果不使用as定义变量,也可以使用 $$this 访问数组中的当前元素
例子2:对超过5元的型号进行查询
db.goods.aggregate([
{
$project: {
types: {
$filter: {
input: "$types",
as: "type",
cond: { $gt: [ "$$type.price", 5 ] }
}
}
}
}
])
聚合查询的结果如下:
{ "_id" : 1, "types" : [ { "size" : "S", "quantity" : 10, "price" : 8 }, { "size" : "L", "quantity" : 8, "price" : 12 } ] }
{ "_id" : 2, "types" : [ { "size" : "L", "quantity" : 5, "price" : 30 } ] }
{ "_id" : 3, "types" : [ { "size" : "L", "quantity" : 6, "price" : 10 } ] }
{ "_id" : 4, "types" : [ ] }