【问题标题】:Mongodb aggregate query with condition带有条件的MongoDB聚合查询
【发布时间】:2021-01-11 15:36:39
【问题描述】:

我必须在 python 中对 mongodb 执行聚合,但无法这样做。

下面是提取的mongodb文档结构:

{'Category': 'Male',
 'details' :[{'name':'Sachin','height': 6},
             {'name':'Rohit','height': 5.6},
             {'name':'Virat','height': 5}
            ]
}

我想通过聚合函数返回名称为 Sachin 的高度。基本上我的想法是通过 $match 应用条件提取数据并同时使用聚合函数进行聚合。这可以通过使用 if 语句分 3 个步骤轻松完成,但我希望在 1 个聚合函数中完成。

请注意:'details' 值没有固定长度。

如果需要更多解释,请告诉我。

【问题讨论】:

    标签: python mongodb mongodb-query aggregate-functions


    【解决方案1】:

    你可以做一个$filter来实现

    db.collection.aggregate([
      {
        $project: {
          details: {
            $filter: {
              input: "$details",
              cond: {
                $eq: [
                  "$$this.name",
                  "Sachin"
                ]
              }
            }
          }
        }
      }
    ])
    

    工作Mongo playground

    如果你在find中使用,但你需要注意positional operator

    db.collection.find({
      "details.name": "Sachin"
    },
    {
      "details.$": 1
    })
    

    工作Mongo playground

    如果您需要将其作为对象,您可以简单地使用$arrayElemAr$ifNull

    【讨论】:

      猜你喜欢
      • 2017-02-22
      • 1970-01-01
      • 2018-07-09
      • 2020-11-23
      • 1970-01-01
      • 1970-01-01
      • 2020-02-06
      • 2018-08-16
      相关资源
      最近更新 更多