MongoDB 聚合管道中使用数组表达式运算符过滤数组($filter)

数组表达式运算符主要用于文档中数组的操作,本篇我们主要介绍数组表达式运算符中用于过滤数组的操作,下面我们进行详细介绍:

一、语法

{
   $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" : [ ] }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值