1

I have a collection with items, what i want is a Aggregation where i get all item.recipes.life_skill.names grouped by their names like Heating, Cooking etc

i tried to build the Aggregation but i still have no idea

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

Here is a sample of such a item:

{
   "_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
}

1 Answer 1

0

You need to perform $unwind first to destructure the array.

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

Since you gave only one document, I used composed _id to group

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

This helps to group by each object wise. If you need overall group over all objects, simply use

_id: "$recipes.life_skill.name"

Working Mongo playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.