1

The Problem: I currently have a list of documents that I would like to group by the attribute 'eventType'. The document (representing a song) currently look like this:

Song Document:
{
    id: ID,
    eventType: String,
    numberOfLikes: Integer,
    sections: String[]
}

Result: I would like to have these grouped by eventType, like as follows:

eventType: { 
    songs: [{
       songId: ID,
       numberOfLikes: Integer,
       sections: String[]
    }]
}

How would I do this using the MongoDB aggregation pipeline? I am using MongoDB 4.4.

1 Answer 1

1

You can push root object in songs field using $$ROOT,

db.collection.aggregate([
  {
    $group: {
      _id: "$eventType",
      songs: { $push: "$$ROOT" }
    }
  }
])

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.