简体   繁体   中英

MongoDB / Mongoose find number of results before you

Let's say I have a mongoose model with the name "points". I'm ordering it with the column name "points". And finding out my document by passing in my userid to the document column name userid.

How can I be able to find out certain information such as "there are xx persons better than you?"

In this case how many documents that have higher points than you?

How many searches does it need to "loop" through until the match of your document is there?

Query for the user's points and then query for the count of users with points higher than that.

Points.findOne({userId: userId}, (err, doc) => {
    Points.count({points: {$gt: doc.points}}, (err, count) => {
        // do something with count...
    });
});

For scalable performance, you'd want to separately index userId and points . In your schema:

userId: {type: ObjectId, index: true},
points: {type: Number, index: true},
...

This should be faster than any map-reduce solution.

This problem is already solved in another answer https://stackoverflow.com/a/22902445/6386175

You can use mapReduce for small dataset or better, maintain a separate ordered collection.

If you want to use mongoose, the Model object has Model.mapReduce method too with the same syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM