Unrecognized expression '$push' in MONGODB

Viewed 607

This is how my sample QUESTION array is:

[
        {
            "subject": "app development",
            "topic": "dart",
            "subtopic": "flutter2",
            "questionType": "EASY",
            "questionTitle": "how angular works",
        },
        {
            "subject": "app development",
            "topic": "dart",
            "subtopic": "flutter",
            "questionType": "EASY",
            "questionTitle": "how angular works",
            
        },
        {
            "subject": "app development",
            "topic": "javascript",
            "subtopic": "react native",
            "questionType": "EASY",
            "questionTitle": "how angular works",
      
        },
    ]

I need to group the subject field into, and topic into an array.

This is how I want:

{
            "subject": "web development",
            "topics":[{ 
                topicName:"javascript", 
                subtopics:[
                        "react native,
                        "flutter"
                ]
               }]
}

I'm trying to do it this way but this error:

"Unrecognized expression '$push'" shows

{
          $group: {
            _id: "$subject",
            topics: {
              $addToSet: {
                title: "$topic",
                sub: {$push:"$subtopic"},
              },
            },
          },
        },

I need to get an array of grouped subjects and topics and subtopics.

1 Answers

The $group can not support nested operations $addToSet and $push at the same time, you need to divide both the operations into different $group stages,

  • $group by subject and topic and construct the unique array of subtopic using $addToSet
  • $group by only subject and construct the array of topics
  • $project to format and show required fields
[
  {
    $group: {
      _id: {
        subject: "$subject",
        topic: "$topic"
      },
      subtopic: { $addToSet: "$subtopic" }
    }
  },
  {
    $group: {
      _id: "$_id.subject",
      topics: {
        $push: {
          topic: "$_id.topic",
          sub: "$subtopic"
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      subject: "$_id",
      topics: 1
    }
  }
]

Playground

Related