Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-9377

Extend $push or $max to allow collecting "top" N values per _id key in $group phase

    XMLWordPrintable

    Details

      Description

      Syntax

      {$pushFirstN: [<expression>, N]}
      {$pushLastN: [<expression>, N]}
      {$pushMinN: [<expression>, N]}
      {$pushMaxN: [<expression>, N]}
      

      Examples

      > db.coll.insert([
        {_id: "user1", game:"A", score: 2345},
        {_id: "user3", game:"A", score: 100},
        {_id: "user4", game:"A", score: 555},
        {_id: "user7", game:"A", score: 53234}
      ]);
      > db.coll.aggregate([
          {$sort: {score: -1}},
          {$group: {
              _id: "$game",
              leaderBoardUsers: {
                  $pushFirstN: ["$_id", 10]
              }
          }
      ])
      {_id: "A", leaderBoardUsers: ["user7", "user1", "user4", "user3"]}
       
       
      // Example 2
      > db.coll.insert([
        {_id: "user1", game:"A", score: 2345}
        {_id: "user3", game:"A", score: 100}
        {_id: "user4", game:"A", score: 555}
        {_id: "user7", game:"A", score: 53234}
      ]);
      > db.coll.aggregate([
          {$sort: {score: -1}},
          {$group: {
              _id: "$game",
              leaderBoard: {$pushFirstN: [{_id: "$_id", score: "$score"}, 10]}
          }
      ])
      {
        _id: "A",
        leaderBoard: [
          {_id: "user7", score: 53234},
          {_id: "user1", score: 2345},
          {_id: "user4", score: 555},
          {_id: "user3", score: 100}
        ]
      }
      

      Notes

      • This would be the first accumulator to take more than a single argument.

      Errors

      • If the second argument is not a nonnegative integer. If the argument is zero, the result will be an empty array.

      Previous Description:
      Frequently asked by users:

      Analogous to {$group:{_id:"$key", maxval:{$max:"$val"}}} if user needs to gather top N values per key (most recent, highest N, etc) to have ability to do equivalent of {$max:"$val",$limit:5} or $push:{$sort:...,$limit:N} type of idea.

        Attachments

          Issue Links

            Activity

              People

              Votes:
              77 Vote for this issue
              Watchers:
              67 Start watching this issue

                Dates

                Created:
                Updated: