简体   繁体   中英

Mongodb aggregate push with index value of array

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.!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM