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?
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');
findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With