problem while using sort,skip and limit together

18 views
Skip to first unread message

Sajal Pal

unread,
Mar 30, 2017, 1:20:30 AM3/30/17
to mongodb-user
Suppose I have 30 records in a collection, Now I want to fetch 1st 10 records then 2nd 10 then 3rd 10 records. by running the query each time with skip value and Limit value.

Query-1(To fetch 1st 10 records)
db.AutoVertical.aggregate([
{$project : {"DealerName" : "$DealerName", "DealerPhone" : "$DealerPhone",  "DealerAddress" : "$DealerAddress"}},
{$sort :
   {'DealerName': 1}
 },
 {$limit : 10 },
 {$skip : 0} 
])

Query-2(To fetch 2nd 10 records)
db.AutoVertical.aggregate([
{$project : {"DealerName" : "$DealerName", "DealerPhone" : "$DealerPhone",  "DealerAddress" : "$DealerAddress"}},
{$sort :
   {'DealerName': 1}
 },
 {$limit : 10 },
 {$skip : 10} 
])

Query-3(To fetch 3rd 10 records)
db.AutoVertical.aggregate([
{$project : {"DealerName" : "$DealerName", "DealerPhone" : "$DealerPhone",  "DealerAddress" : "$DealerAddress"}},
{$sort :
   {'DealerName': 1}
 },
 {$limit : 10 },
 {$skip : 20} 
])

Now I am facing the issue is that sorting is not working properly. When I run the 1st query I am getting(a,b,c,d....) and then when I am running the 2nd query I am getting (a,b,x,y....).The problem is that I am getting a,b in both the result set.
can any one help me 

Asya Kamsky

unread,
Mar 30, 2017, 5:32:52 PM3/30/17
to mongodb-user
You're doing something strange here - you have $skip after $limit?

That means you are always getting the first 10 records going into
$skip. {$limit:10} followed by {$skip:10} will alway return nothing.

Order matters! At least in aggregation where stages are processed in order.

Asya
> --
> You received this message because you are subscribed to the Google Groups
> "mongodb-user"
> group.
>
> For other MongoDB technical support options, see:
> https://docs.mongodb.com/manual/support/
> ---
> You received this message because you are subscribed to the Google Groups
> "mongodb-user" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to mongodb-user...@googlegroups.com.
> To post to this group, send email to mongod...@googlegroups.com.
> Visit this group at https://groups.google.com/group/mongodb-user.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/mongodb-user/62b330b7-476a-433f-a405-4be24c56b099%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



--
Asya Kamsky
Lead Product Manager
MongoDB
Download MongoDB - mongodb.org/downloads
We're Hiring! - https://www.mongodb.com/careers
Reply all
Reply to author
Forward
0 new messages