简体   繁体   English

MongoDB / Mongoose在您之前查找结果数

[英]MongoDB / Mongoose find number of results before you

Let's say I have a mongoose model with the name "points". 假设我有一个名为“points”的猫鼬模型。 I'm ordering it with the column name "points". 我用列名“points”订购它。 And finding out my document by passing in my userid to the document column name userid. 通过将我的用户标识传递给文档列名称userid来查找我的文档。

How can I be able to find out certain information such as "there are xx persons better than you?" 我怎样才能找到某些信息,例如“有xx人比你好?”

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 . 对于可伸缩性能,您需要单独索引userIdpoints In your schema: 在您的架构中:

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

This should be faster than any map-reduce solution. 这应该比任何map-reduce解决方案都快。

This problem is already solved in another answer https://stackoverflow.com/a/22902445/6386175 此问题已在另一个答案https://stackoverflow.com/a/22902445/6386175中得到解决

You can use mapReduce for small dataset or better, maintain a separate ordered collection. 您可以将mapReduce用于小型数据集或更好,维护单独的有序集合。

If you want to use mongoose, the Model object has Model.mapReduce method too with the same syntax. 如果要使用Model.mapReduce ,Model对象也具有相同语法的Model.mapReduce方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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