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

1 Answer 1

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

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.