MongoDB通过聚合分组

弗洛里安·霍夫迈斯特

我有一个包含项的集合,我想要的是一个聚合,其中我得到了所有item.recipes.life_skill.names按名称进行分组,如加热,烹饪等

我试图建立聚合,但我仍然不知道

{
  _id: "recipes.life_skill.name",
  "life_skill": {
    $first: "recipes.life_skill.name"
  }
}

这是此类物品的示例:

{
   "_id": {
      "$oid": "5f87ddc65a997f69083d663d"
   },
   "id": "756005",
   "global_id": "item--756005",
   "category": "Special Items",
   "name": "Lunar Black Stone",
   "grade": 3,
   "weight": "0.01",
   "required_level": 1,
   "url": null,
   "icon_url": null,
   "recipes": [{
       "global_id": "mrecipe--2103",
       "id": "2103",
       "life_skill": {
           "name": "Heating",
           "rank": "Beginner",
           "level": 1
       },
       "xp_amount": null,
       "url": null,
       "input_products": [{
           "type": "ITEM",
           "id": "756002",
           "name": "Frosted Black Stone",
           "quantity": 10,
           "url": null
       }, {
           "type": "ITEM",
           "id": "756003",
           "name": "Starlight Crystal",
           "quantity": 1,
           "url": null
       }],
       "output_products": [{
           "type": "ITEM",
           "id": "756005",
           "name": "Lunar Black Stone",
           "quantity": 1,
           "url": null
       }],
       "product_groups": []
   }],
   "used_in_recipes": null,
   "ship_upgrades": null,
   "achievements": null
}
当然

您需要首先执行$unwind以解构阵列。

db.collection.aggregate([
  {
    $unwind: "$recipes"
  },
  {
    $group: {
      _id: {
        _id: "$_id",
        life_skill: "$recipes.life_skill.name"
      },
      life_skill: {
        $first: "$recipes.life_skill.name"
      }
    }
  }
])

由于您只给出了一个文档,所以我习惯于_id组合

_id: {
        _id: "$_id",
        life_skill: "$recipes.life_skill.name"
      }

这有助于按对象明智地分组。如果您需要对所有对象进行整体分组,只需使用

_id: "$recipes.life_skill.name"

工作蒙戈游乐场

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章