problem while using sort,skip and limit together

16 views
Skip to first unread message

Sajal Pal

unread,
Mar 29, 2017, 4:17:09 PM3/29/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 
Message has been deleted

compchap.nikhil

unread,
Mar 30, 2017, 6:36:42 PM3/30/17
to mongodb-user
Hi Sajal

Try this, it will work.

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

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

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

Thanks,
Nikhil
Reply all
Reply to author
Forward
0 new messages