Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 825
maria Avatar asked Sep 21 '16 21:09

maria


People also ask

How do you use Mongoose count?

var db = mongoose. connect('mongodb://localhost/myApp'); var userSchema = new Schema({name:String,password:String}); userModel =db. model('UserList',userSchema); var userCount = userModel. count('name');

What does findById return in Mongoose?

findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .

What is skip in Mongoose?

In Mongoose, the skip() method is used to specify the number of documents to skip. When a query is made and the query result is returned, the skip() method will skip the first n documents specified and return the remaining.

What is findById in Mongoose?

Mongoose | findById() Function The findById() function is used to find a single document by its _id field. The _id field is cast based on the Schema before sending the command.


2 Answers

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.

like image 51
JohnnyHK Avatar answered Oct 20 '22 18:10

JohnnyHK


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.

like image 28
Dario Avatar answered Oct 20 '22 18:10

Dario