2

I am stucked in one aggregate query, Following is my data

Let database = [
{
 _id: 'fefesf', name: 'John', info: {date: ISODate(), marks: '12'}
},
{
 _id: 'uiuioo', name: 'John', info: {date: ISODate(), marks: '15'}
},
{
 _id: 'erygbo', name: 'Ben', info: {date: ISODate(), marks: '18'}
}]

and my aggregate query is

var query = [{
  $group: {
   _id: '$name',
   Marks: {
     $push: {
       x: '$index',  ..............(not working right now)
       y: '$info.marks'
     }
   }
 }
}]

Is it possible to get index of grouped document as 'x' while pushing it in 'Marks' array. Like Output should be

[
 {_id: 'John', Marks: [{x: 1, y: 12}, {x: 2, y: 15}]},
 {_id: 'Ben',{x: 1, y: 18}}
] 

Thanks in advance.!

aryan
  • 163
  • 1
  • 1
  • 11

1 Answers1

0

Since mongoDB version 3.6 you can use $reduce for that*:

db.collection.aggregate([
  {
    $group: {
      _id: "$name",
      Marks: {$push: {y: "$info.marks"}}
    }
  },
  {$project: {
      Marks: {
        $reduce: {
          input: "$Marks",
          initialValue: [],
          in: {$concatArrays: [
              "$$value",
              [
                {
                  y: "$$this.y",
                  x: {$add: [{$size: "$$value"}, 1]}
                }
              ]
            ]
          }
        }
      }
    }
  }
])

See how it works on the playground example

*Inspired by this answer

nimrod serok
  • 14,151
  • 2
  • 11
  • 33