mongodb 查询mongodb的前N行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20727257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:32:28  来源:igfitidea点击:

Query on top N rows in mongodb

mongodb

提问by kishore

I want to fetch 100 records from a student collection sort by name. Now i want to get student who has marks greater than x in this 100 records only. Can any one please help in solving this. When i give Max(marks) in query it is executing before the sort and skip.

我想从学生集合中按名称排序获取 100 条记录。现在我只想让学生在这 100 条记录中的分数大于 x。任何人都可以帮助解决这个问题。当我在查询中给出 Max(marks) 时,它在排序和跳过之前执行。

This the query i tried

这是我试过的查询

var query = {};
query["marks"] = {$gt:35};
db.collection("student").find(query).skip(0).limit(100).sort("name")

回答by JohnnyHK

When your query is described in steps as in this case, the ability of aggregateto pipeline results from the output of one operation to the input of the next makes it a natural choice:

当您的查询在这种情况下按步骤进行描述时,将aggregate结果从一个操作的输出传输到下一个操作的输入的能力使其成为一个自然的选择:

db.student.aggregate([
    // First sort all the docs by name
    {$sort: {name: 1}},
    // Take the first 100 of those
    {$limit: 100},
    // Of those, take only ones where marks > 35
    {$match: {marks: {$gt: 35}}}
])

回答by Vicky

You can do this by applying your condition on the cursor. So first select the rows from database and then apply the condition on cursor returned by find query.

您可以通过在光标上应用您的条件来做到这一点。因此,首先从数据库中选择行,然后在查找查询返回的游标上应用条件。

   db.student.find().limit(100).sort({"name":1}).forEach( function(doc){ 
                                       if(doc.marks >35) { print(doc.marks); } 
                                                 });

or

或者

    var cursor = db.student.find().limit(100).sort({"name":1});
    cursor.forEach(function(doc){ if(doc.marks >35){ print(doc.marks); } } );

These above queries are doing same thing. They will first fetch the records from the database and then will print marks of all the documents which have marks greater then 35.

上述这些查询正在做同样的事情。他们将首先从数据库中获取记录,然后打印所有标记大于 35 的文档的标记。