S
S
sldo_ru2020-05-12 23:23:00
MongoDB
sldo_ru, 2020-05-12 23:23:00

How to filter by descending field in mongoDB?

There is a user model with a count and all field, you need to display 10 users with the largest number from subtracting all and count.

Let's say the first user has count = 5, all = 10; the second has count = 2, all = 20;

They need to be displayed from largest to smallest, how to do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sldo_ru, 2020-05-13
@sldo_ru

User.aggregate([{
            $project:
                {
                    min: { $subtract: ['$all', '$count'] },
                },
        }, {$limit: 10}, {$sort: {min: -1}}], function (err, data) {
            console.log(data);
        });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question