The JOKER
The JOKER

Reputation: 473

multilevel grouping in MongoDB Query

I'm trying to write a query where it will give the result of multilevel grouping.

Like below:

firstLevel: [
    {
       SecondLevel-1:
       [
              {//Some Data},
              {//Some Data}
       ]
    },
    {
       SecondLevel-2:
       [
              {//Some Data},
              {//Some Data}
       ]
    }
]

Below is my MongoPlayGround URL

https://mongoplayground.net/p/b7VzoXavw9r

I'm able to get the first level grouping, although I want the result in the below format.

    [
  {
    "section-1": [
      {
        "terminal-1":[
                {
            "_id": ObjectId("5e93fea52f804ab99b12e7c0"),
            "isActive": true,
            "isDelete": false
          },
          {
            "_id": ObjectId("5e93fea52f804ab99b12e7c1"),
            "isActive": true,
            "isDelete": false
          }
        ]
      },
      "terminal-2":[
                {
                     "_id": ObjectId("5e93fea52f804ab99b12e7c2"),
                    "isActive": true,
                    "isDelete": true
                }
        ]
    ]
  }
]

Upvotes: 0

Views: 134

Answers (1)

turivishal
turivishal

Reputation: 36104

  • $group by section and terminal, make unique array of terminal
  • $group by section and make key value pair of terminal array
  • $arrayToObject convert key and value array to object
  • $replaceRoot to replace object in root after converting to object
db.settings.aggregate([
  {
    $group: {
      _id: {
        section: "$section",
        terminal: "$terminal"
      },
      v: {
        $addToSet: {
          _id: "$_id",
          isActive: "$isActive",
          isDelete: "$isDelete"
        }
      }
    }
  },
  {
    $group: {
      _id: "$_id.section",
      v: {
        $push: { k: "$_id.terminal", v: "$v" }
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        $arrayToObject: [[
            {
              k: "$_id",
              v: { $arrayToObject: "$v" }
            }
        ]]
      }
    }
  }
])

Playground

Upvotes: 1

Related Questions