Search code examples
node.jsmongodbaggregation-frameworkprojection

MongoDB : Group by rounded value


Let's take an example :

{ _id: "xx", total: 12345, name: "Bob" }
{ _id: "xa", total: 123, name: "Bob" }
{ _id: "xb", total: 1290, name: "Bob" }
{ _id: "xc", total: 1255, name: "Bob" }

I would like to have something like :

[
  { name: '100', count: 1 },
  { name: '1000', count: 2 },
  { name: '10000', count: 1 }
]

Actually i work with $project, $concat and $group. It works but i have 2 problem :

  1. I would like to sort like my exemple (100, 1000, 10000) and i really don't know how i can do this
  2. Actually it works with $concat. I have to write every case so it seems to be the wrong way. After some research i found that $round can take a negative number.

In my case : 123 could be 100 with $round(123, -2). But how can i have dynamically my negative factor ?

Yeah i really need help.

Thanks & Regards,


Solution

  • This aggregation should solve your issue:

    db.collection.aggregate([
      {
        $addFields: {
          place: {
            $multiply: [
              {
                $add: [
                  {
                    $strLenCP: {
                      $toString: "$total",
                    },
                  },
                  -1,
                ],
              },
              -1,
            ],
          },
        },
      },
      {
        $project: {
          name: {
            $round: ["$total", "$place"],
          },
        },
      },
      {
        $group: {
          _id: "$name",
          count: {
            $sum: 1,
          },
        },
      },
      {
        $project: {
          name: {
            $toString: "$_id",
          },
          count: 1,
          _id: 0,
        },
      },
      {
        $sort: {
          name: 1,
        },
      },
    ])