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 :
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,
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,
},
},
])