Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query on top N rows in mongodb

Tags:

mongodb

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.

This the query i tried

var query = {};
query["marks"] = {$gt:35};
db.collection("student").find(query).skip(0).limit(100).sort("name")
like image 339
kishore Avatar asked Dec 22 '13 07:12

kishore


People also ask

How do I get all rows in MongoDB?

Fetch all data from the collection If we want to fetch all documents from the collection the following mongodb command can be used : >db. userdetails. find(); or >db.

How do I use $in in MongoDB?

Use the $in Operator to Match Values This query selects all documents in the inventory collection where the value of the quantity field is either 5 or 15. Although you can write this query using the $or operator, use the $in operator rather than the $or operator when performing equality checks on the same field.

How do I search for a query in MongoDB?

Use the $text query operator to perform text searches on a collection with a text index. $text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.


1 Answers

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

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}}}
])
like image 126
JohnnyHK Avatar answered Sep 18 '22 13:09

JohnnyHK