Query to make a rank

Hi @foco_radiante - Thank you for providing the schema.

So the rank would be, of course:
Eraser - 8
Pencil - 5

I am not entirely sure this is the exact output you are after but please see the following from my test environment:

itemsdb> db.testcoll.find()
[
  { _id: 0, name: “Eraser” },
  { _id: 1, name: “Eraser” },
  { _id: 2, name: “Eraser” },
  { _id: 3, name: “Eraser” },
  { _id: 4, name: “Eraser” },
  { _id: 5, name: “Eraser” },
  { _id: 6, name: “Eraser” },
  { _id: 7, name: “Eraser” },
  { _id: 8, name: “Pencil” },
  { _id: 9, name: “Pencil” },
  { _id: 10, name: “Pencil” },
  { _id: 11, name: “Pencil” },
  { _id: 12, name: “Pencil” }
]

$group based on the “name” field:

itemsdb> db.testcoll.aggregate({$group:{_id:‘$name’,count:{$sum:1}}})
[ 
{ _id: ‘Eraser’, count: 8 }, 
{ _id: ‘Pencil’, count: 5 }
]

I would refer to the following documentation regarding the details of the aggregation stages / operators used in my above example:

Additionally, you may also find the M121 - The MongoDB Aggregation Framework course useful.

Hope this helps.

Regards,
Jason

3 Likes