提问者:小点点

MongoDB计数,最小,最大,平均使用带有对象列表的字段进行聚合


我在使用MongoDB集合获取统计数据时遇到问题。

收藏

[
  {
    "_id": {"$oid": "616309f71b021c754992bfca"},
    "correlatedNodes": [
      {
        "type": "IS_ULTIMATELY_CONSOLIDATED_BY",
        "nodes": ["I07WOS4YJ0N7YRFE7309"]
      }
    ],
    "fromTaskId": 20,
    "nodeName": "5493000U0YGG4VEQOX65"
  },
  {
    "_id": {"$oid": "616309f71b021c754992bfcb"},
    "correlatedNodes": [
      {
        "type": "IS_DIRECTLY_CONSOLIDATED_BY",
        "nodes": ["529900P6OUCFPVWCFE19", "8945007IZBKFQUQLIP85"]
      },
      {
        "type": "IS_ULTIMATELY_CONSOLIDATED_BY",
        "nodes": ["529900P6OUCFPVWCFE19"]
      }
    ],
    "fromTaskId": 20,
    "nodeName": "89450012XZ2GPWGIGH37"
  },
  {
    "_id": {"$oid": "616309f71b021c754992bfcc"},
    "correlatedNodes": [
      {
        "type": "IS_ULTIMATELY_CONSOLIDATED_BY",
        "nodes": ["815600C9588783AB0210"]
      },
      {
        "type": "IS_DIRECTLY_CONSOLIDATED_BY",
        "nodes": ["815600C9588783AB0210"]
      }
    ],
    "fromTaskId": 20,
    "nodeName": "815600228127946DFF05"
  },
  {
    "_id": {"$oid": "616309f71b021c754992bfcd"},
    "correlatedNodes": [
      {
        "type": "IS_ULTIMATELY_CONSOLIDATED_BY",
        "nodes": ["549300LI58A0MHGHTZ98"]
      }
    ],
    "fromTaskId": 20,
    "nodeName": "549300NV4OCF16TAS048"
  }
]

我想获取correlatedNodes字段的基本统计信息。

像这样的东西:

{
  "IS_ULTIMATELY_CONSOLIDATED_BY": {
      "count": 567,
      "avg": 22,
      "min": 3,
      "max": 50
    }
}

通过计数,我的意思是为每种连接类型使用列表大小。

我尝试了这样的聚合查询:

db.node_correlations.aggregate([
    {
        $project: {"correlatedNodes":  "$correlatedNodes" },
        $unwind: "$correlatedNodes"
    }
]);

但我收到错误:

[2021-10-13 12:14:10]com.mongoDB.MongoCommand dException:命令失败,错误40323(Location40323):'管道阶段规范对象必须仅包含一个字段。'在服务器localhost:27017上。完整响应是{"ok":0.0,"errmsg":"管道阶段规范对象必须仅包含一个字段。","code":40323,"codeName":"Location40323"}


共1个答案

匿名用户

谢谢大家的帮助。

工作解决方案是:

db.node_correlations.aggregate([
  {
    "$unwind": "$correlatedNodes"
  },
  {
    "$group": {
      "_id": "$correlatedNodes.type",
      "count": {
        "$sum": {"$size": "$correlatedNodes.nodes"}
      },
      "avg": {
        "$avg": {"$size": "$correlatedNodes.nodes"}
      },
      "min": {
        "$min": {"$size": "$correlatedNodes.nodes"}
      },
      "max": {
        "$max": {"$size": "$correlatedNodes.nodes"}
      }
    }
  }
])