Query to make a rank

Hey, I have the following schema:

const Objects = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    utility: {
        type: String,
        required: true,
    },
    createdAt: {
        type: Date,
        default: Date.now,
    }
})

What I want to do is to pick all data, for example, and then, make a rank of the objects.
For example, lets suppose the collection has 5 documents with the name “Pencil”, and then 8 documents with the name “Eraser”.

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

But I don’t know the names of the objects to apply some $match or something, I need to get it from the data…

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

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.