Blog Post

MongoDB : How to get Top, Bottom,Middle and Range of records

,

In MongoDB,the limit() method is used to limit the result set to be returned. You can also use this with various methods such as sort() and skip() for various combination of requirement.

The MS SQL equivalent is TOP function

>SELECT TOP 10 * FROM <TABLENAME>

Some examples are

Top ‘N’Record

db.categories.find().sort({$natural:1}).limit(10 )

Bottom ‘N’ Record

db.categories.find().sort({$natural:-1}).limit(10 )

Middle Record

db.categories.find().skip(db.categories.count()/2).limit(1)

Range of records from 3 and then select 4 records

>var startRange=3
> var EndRange=4
> db.categories.find().skip(startRange).limit(EndRange)

Output:

TopMiddle

 

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating