【问题标题】:Fetch only those array elements in mongodb that satisfy the condition仅获取 mongodb 中满足条件的数组元素
【发布时间】:2022-01-08 14:30:12
【问题描述】:

假设我在 MongoDB 中有以下测试集合:

[
  {name: "vipul",arr:[1,2,3,4,5,6,7,8]},
  {name: "rahul",arr:[3,4,5,6,7,8,9,10]},
]

现在,如果我执行以下查询:

db.test.find({"arr":{$gt: 5});

上述查询返回以下输出:

[
  {name: "vipul",arr:[1,2,3,4,5,6,7,8]},
  {name: "rahul",arr:[3,4,5,6,7,8,9,10]},
]

但我只需要那些符合条件的元素,如下所示:

[
  {name: "vipul",arr:[6,7,8]},
  {name: "rahul",arr:[6,7,8,9,10]},
]

我知道这可以使用聚合来完成,但我想在没有聚合的情况下做到这一点。有什么办法吗??

谢谢!

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    为投影中的arr 字段添加$filter

    db.collection.find({
      "arr": {
        $gt: 5
      }
    },
    {
      "name": 1,
      "arr": {
        $filter: {
          input: "$arr",
          cond: {
            $gt: [
              "$$this",
              5
            ]
          }
        }
      }
    })
    

    Sample Mongo Playground

    【讨论】:

      猜你喜欢
      • 2011-04-16
      • 2017-08-09
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 2018-12-08
      • 2020-10-22
      • 2018-07-26
      相关资源
      最近更新 更多