1

My mongo data are in the following format:

{ country: "Bangladesh", city: "Dhaka", name: "Jobayer", email: "[email protected]" }
{ country: "Bangladesh", city: "Dhaka", name: "Mehotaz", email: "[email protected]" }
{ country: "KSA", city: "Dammam", name: "Jabal", email: "[email protected]" }

I want to retrieve data like below:

[
    {
        country: 'Bangladesh',
        cities: [
            {
                city: 'Dhaka',
                contacts: [
                    {
                        name: 'Jobayer',
                        email: '[email protected]'
                    },
                    {
                        name: 'Mehotaz',
                        email: '[email protected]'
                    }
                ]
            }
        ]
    },
    {
        country: 'KSA',
        cities: [
            {
                city: 'Dammam',
                contacts: [
                    {
                        name: 'Jabal',
                        email: '[email protected]'
                    }
                ]
            }
        ]
    }
];

I have tried some group operations but could not get the expected result. Please provide your valuable suggestion on how can I achieve that.

1 Answer 1

3

What you want to do is $group twice, once on country x city and then on just the country, like so:

db.collection.aggregate([
  {
    $group: {
      _id: {
        country: "$country",
        city: "$city"
      },
      contacts: {
        $push: {
          name: "$name",
          email: "$email"
        }
      }
    }
  },
  {
    $group: {
      _id: "$_id.country",
      cities: {
        $push: {
          city: "$_id.city",
          contacts: "$contacts"
        }
      }
    }
  }
])

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.