Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo doesn't maintain $sort order after $skip when sort values are same

My data looks like this:

{ _id: 1, x: "abc", y: "def"}
{ _id: 2, x: "abc", y: "efg"}
{ _id: 3, x: "xxx", y: "xxx"}

My query looks like this:

db.col.aggregate([{ $sort: { x: 1 } },{ $skip: 0 } ])

When I run that query, i see everything in order: 1, 2, 3 When I change skip to 1, i get 1,3 When it does the sort, is it internally recognizing that docs 1 and 2 are sorted on the same value and using a different method to choose which to use if skipping? Is there any way around this?

like image 431
DAB Avatar asked Sep 02 '25 14:09

DAB


1 Answers

Your query is right may be version issue create problem

db.col.aggregate([{ $sort: { x: 1, _id: 1 } }, { $skip: 1 } ])

you can use sort and skip

db.col.find({ }).sort( { x: 1, _id: 1 } ).skip(1);

Skip is used number of first n doc skip. Mongodb not have offset like mysql

like image 117
Ashok Avatar answered Sep 05 '25 12:09

Ashok