【问题标题】:PyMongo - Change output formatPyMongo - 更改输出格式
【发布时间】:2022-11-10 09:15:44
【问题描述】:

这是我在 PyMongo 中用来获取值的 MongoDB 查询:

query = [{"$match": {"scheduledAt": {"$gte": startTime, "$lt": endTime}}},
         {"$project": {"_id": "$type","countss": {"$cond": {"if": {"match$isArray": "$inputUrls"},"then": {"$size": "$inputUrls"},"else": "NA"}}}},
         {"$group": {"_id":"$_id","total_count":{"$sum": "$countss"}}}]

我得到的输出:

[
  {_id: 'a', total_count: 3},
  {_id: 'b', total_count: 2}
]

所需输出:

[
  {'a': 3},
  {'b': 2}
]

【问题讨论】:

  • 您可能希望显示 1 或 2 个输入文档,以更好地了解您的漂亮查询如何产生初始输出。

标签: mongodb mongodb-query aggregation-framework pymongo


【解决方案1】:

你需要$replaceRoot 舞台作为末期使用$arrayToObject 将文档转换为键值对。

{
  "$replaceRoot": {
    "newRoot": {
      "$arrayToObject": [
        [
          {
            k: "$_id",
            v: "$total_count"
          }
        ]
      ]
    }
  }
}

Sample Mongo Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多