MST

星途 面试题库

面试题:MongoDB中如何使用数组表达式在聚合框架里筛选特定元素

假设有一个集合,文档结构如下:{ _id: ObjectId('64a9f85762967d9b98a2c977'), items: [ { name: 'item1', quantity: 5 }, { name: 'item2', quantity: 3 }, { name: 'item3', quantity: 7 } ] }。请使用聚合框架和数组表达式,筛选出items数组中quantity大于4的元素。
14.8万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试

在MongoDB中,可以使用以下聚合框架和数组表达式来解决这个问题:

[
    {
        "$project": {
            "filteredItems": {
                "$filter": {
                    "input": "$items",
                    "as": "item",
                    "cond": { "$gt": [ "$$item.quantity", 4 ] }
                }
            }
        }
    }
]
  1. $project阶段:用于选择输出的字段,并使用$filter数组表达式来筛选items数组中的元素。
  2. $filter表达式
    • input指定要过滤的数组,这里是$items,即文档中的items数组。
    • as给数组中的每个元素定义一个别名,这里是item
    • cond是过滤条件,使用$gt比较运算符,判断当前元素(通过$$item引用)的quantity字段是否大于4。满足条件的元素将被保留在filteredItems数组中。