Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unwind the _id field of a mogodb aggregation stage

I want to unwind a group of fields but seems like unwind doesn’t work on _id field. I want to unwind the output because I want to write it in a new collection.

Here is an example showing what I want to do:

Some data:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

db.test.insertOne({A: "A1", B: "B1", num:1})
db.test.insertOne({A: "A2", B: "B2", num:2})
db.test.insertOne({A: "A1", B: "B2", num:3})
db.test.insertOne({A: "A2", B: "B1", num:4})
db.test.insertOne({A: "A1", B: "B1", num:5})
db.test.insertOne({A: "A2", B: "B2", num:6})
db.test.insertOne({A: "A1", B: "B2", num:7})
db.test.insertOne({A: "A2", B: "B1", num:8})

My aggregation stage:

db.test.aggregate([
    { 
    $group: { 
            _id: {A:"$A",B:"$B"}, 
            sum: { $sum: "$num" } 
           } 
    },
    {
    $unwind: _id
    }
])

The output:

{ _id: { A: 'A1', B: 'B2' }, sum: 10 }
{ _id: { A: 'A2', B: 'B2' }, sum: 8 }
{ _id: { A: 'A1', B: 'B1' }, sum: 6 }
{ _id: { A: 'A2', B: 'B1' }, sum: 12 }

My desired output:

{ A: 'A1', B: 'B2', sum: 10 }
{ A: 'A2', B: 'B2', sum: 8 }
{ A: 'A1', B: 'B1', sum: 6 }
{ A: 'A2', B: 'B1', sum: 12 }

I tried the following unwind code but it doesn’t affect the result:

db.test.aggregate([
    { 
    $group: { 
            _id: {A:"$A",B:"$B"}, 
            sum: { $sum: "$num" } 
           } 
    },
    {
    $unwind: "$_id"
    }
])

>Solution :

$unwind stage isn’t suitable for your scenario.

Instead, you need a $project stage instead of $unwind stage.

{
  $project: {
    _id: 0,
    A: "$_id.A",
    B: "$_id.B",
    sum: 1
  }
}

Demo @ Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading