mongoDB 如何对 subdocument 进行 $group?

新手上路,请多包涵

问题描述

两个 Collection: teams, scores.
teams 中的 score 是一个 Array, 字段关联 scores_id.
现要查 teams 并对其中的 score 根据它的 round 字段做统计。
但我只能做到从 scores Collection 中把所有相关的值查出来,不知道如何统计。

teams 的结构如下:

/* 1 */
{
    "_id" : ObjectId("5b963f96219e2651faaf1d1b"),
    "title" : "中国队",
    "number" : "01",
    "description" : "养江花目严华机果门种你点把南准料影八率大。",
    "score" : [ 
        ObjectId("5b9a1ced72b68d055a2f56e6"), 
        ObjectId("5b9a1d6cdb831f08d251c24c"), 
        ObjectId("5b9a1dbedb831f08d251c24d"), 
    ]
}

/* 2 */
{
    "_id" : ObjectId("5b963f96219e2651faaf1d1c"),
    "title" : "塞浦路斯队",
    "number" : "02",
    "description" : "多最的式属平众原开五方严米件个商省单报亲。",
    "score": []
}

scores 结构如下:

/* 1 */
{
    "_id" : ObjectId("5b965604e9095d7cfb289ea8"),
    "team" : ObjectId("5b963f96219e2651faaf1d1b"),
    "round" : ObjectId("5b8e5467759a584980dbe33b"),
    "value" : 22,
}

/* 2 */
{
    "_id" : ObjectId("5b965610e9095d7cfb289ea9"),
    "team" : ObjectId("5b963f96219e2651faaf1d1b"),
    "round" : ObjectId("5b8e5467759a584980dbe33c"),
    "value" : 221,
}

/* 3 */
{
    "_id" : ObjectId("5b965614e9095d7cfb289eaa"),
    "team" : ObjectId("5b963f96219e2651faaf1d1b"),
    "round" : ObjectId("5b8e5467759a584980dbe33b"),
    "value" : 98,
}

自己尝试过哪些方法,相关代码

db.getCollection('teams').aggregate([
  {
    $lookup: {
      from: 'scores',
      localField: 'score',
      foreignField: '_id',
      as: 'score'
    }
  }
])

我用上面代码可以查出下面的数据:

{
    "_id" : ObjectId("5b963f96219e2651faaf1d1b"),
    "title" : "中国队",
    "number" : "01",
    "description" : "养江花目严华机果门种你点把南准料影八率大。",
    "score" : [ 
        {
            "_id" : ObjectId("5b9a1ced72b68d055a2f56e6"),
            "team" : ObjectId("5b963f96219e2651faaf1d1b"),
            "round" : ObjectId("5b8e5467759a584980dbe33b"),
            "value" : 228
        }, 
        {
            "_id" : ObjectId("5b9a1d6cdb831f08d251c24c"),
            "team" : ObjectId("5b963f96219e2651faaf1d1b"),
            "round" : ObjectId("5b8e5467759a584980dbe33b"),
            "value" : 18,
        }, 
        {
            "_id" : ObjectId("5b9a1dbedb831f08d251c24d"),
            "team" : ObjectId("5b963f96219e2651faaf1d1b"),
            "round" : ObjectId("5b8e5467759a584980dbe33c"),
            "value" : 128,
        },
    ]
}

你期待的结果是什么?

可以对 score 字段中的 round 进行统计,例如:

{
    "_id" : ObjectId("5b963f96219e2651faaf1d1b"),
    "title" : "中国队",
    "number" : "01",
    "description" : "养江花目严华机果门种你点把南准料影八率大。",
    "score" : [ 
        {
            "round" : ObjectId("5b8e5467759a584980dbe33c"),
            "count": 2,
            "total" : 228
        }, 
        {
            "round" : ObjectId("5b8e5467759a584980dbe33b"),
            "count": 1,
            "total" : 1328,
        }, 
    ]
}

如果有需要我可以提供数据库文件。
mongoDB version: 3.6.x, 可以升级。

提供思路或 伪代码/代码 都可以,谢谢。

阅读 1.5k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进