1

I have a collection with documents like the following:

{
  "towers": [
    {
      "name": "foo",
      "towers": [
        {
          "name": "A",
          "buildType": "Apartament"
        },
        {
          "name": "B",
          "buildType": "Apartament"
        }
      ]
    },
    {
      "name": "xpto",
      "towers": [
        {
          "name": "C",
          "buildType": "House"
        },
        {
          "name": "D",
          "buildType": "Office"
        }
      ]
    }
  ]
}

All I need to know is what are all the possible values for "buildType", like:

  • Apartment
  • House
  • Office

It's a complex object and the data to aggregate is deep inside it. Is there any way to achieve the results I want?

2 Answers 2

1

You need to $unwind the two nested array that is "towers" and "towers.towers" and then use $group with "towers.towers.buildType" field to get the distinct values

db.collection.aggregate([
  { "$unwind": "$towers" },
  { "$unwind": "$towers.towers" },
  { "$group": {
    "_id": "$towers.towers.buildType"
  }}
])

Output

[
  {
    "_id": "Office"
  },
  {
    "_id": "House"
  },
  {
    "_id": "Apartament"
  }
]
Sign up to request clarification or add additional context in comments.

Comments

0
db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $unwind: {
                path: "$towers",

            }
        },

        // Stage 2
        {
            $unwind: {
                path: "$towers.towers",
            }
        },

        // Stage 3
        {
            $group: {
                _id: '$_id',
                buildType: {
                    $addToSet: '$towers.towers.buildType'
                }
            }
        },

    ]



);

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.