Reputation: 598
Suppose I have collection foo:
> db.foo.find()
{ "_id" : ObjectId("5076865a72da558dd40c819d"), "a" : 1, "b" : 5 }
{ "_id" : ObjectId("5076866f5c70b3b37c048494"), "a" : 2, "b" : 4 }
{ "_id" : ObjectId("5076866f5c70b3b37c048495"), "a" : 3, "b" : 6 }
{ "_id" : ObjectId("507686835c70b3b37c048496"), "a" : 0, "b" : 4 }
I want to sort it by b
, then by a
:
> db.foo.find().sort({b:-1,a:-1})
{ "_id" : ObjectId("5076866f5c70b3b37c048495"), "a" : 3, "b" : 6 }
{ "_id" : ObjectId("5076865a72da558dd40c819d"), "a" : 1, "b" : 5 }
{ "_id" : ObjectId("5076866f5c70b3b37c048494"), "a" : 2, "b" : 4 }
{ "_id" : ObjectId("507686835c70b3b37c048496"), "a" : 0, "b" : 4 }
Apparently, hash passed to sort() preserves the order of keys:
> db.foo.find().sort({a:-1,b:-1})
{ "_id" : ObjectId("5076866f5c70b3b37c048495"), "a" : 3, "b" : 6 }
{ "_id" : ObjectId("5076866f5c70b3b37c048494"), "a" : 2, "b" : 4 }
{ "_id" : ObjectId("5076865a72da558dd40c819d"), "a" : 1, "b" : 5 }
{ "_id" : ObjectId("507686835c70b3b37c048496"), "a" : 0, "b" : 4 }
What I need is to duplicate this behavior in Node.js application that uses mongoosejs as DB wrapper. I know that with one sorting parameter I can go with
Foo.find({},[],{sort:{b:-1}}, callback)
Having two parameters confuses me as both Foo.find({},[],{sort:{b:-1, a:-1}}, callback)
and Foo.find({},[],{sort:{a:-1, b:-1}}, callback)
return the elements in the same order (sorted by a
) - as it should, as obviously hashes/objects have no key order.
I know that you can pass arrays(e.g. ['b','a']
), but am still unsure how to set reverse order: ['-b','-a']
, although being recoginzed by mongoosejs, sorts in direct order.
Upvotes: 0
Views: 364
Reputation: 311835
In Mongoose 3.x you can pass a string into Query#sort to do this:
Foo.find().sort('-b -a').exec(callback);
Upvotes: 1