Home > front end >  MongoDB - Unwind the _id field in an aggregation stage
MongoDB - Unwind the _id field in an aggregation stage

Time:10-10

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:

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"
    }
])

CodePudding user response:

$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

  • Related