Reputation: 657
Is it possible to have documents returned in the order they were requested, if using $in and searching for _id? Is there anyway to sort the output by the order in the query?
From the docs, there is an example like this:
db.things.find({j:{$in: [4,2,6]}});
So let's presume we want this query:
db.things.find({_id:{$in: [4,2,6]}});
and the result to be ordered by 4,2,6 (the document ids, in the order in the array in the query).
Upvotes: 1
Views: 246
Reputation: 1
also can do like this
db.things.find({_id:{$in: [4,2,6]}}).sort({_id:1});
Upvotes: 0
Reputation: 27080
Some more detail would help ... but .sort() should do the trick ...
You can use it in a couple ways, like ORDER BY in SQL ...
Sorting by FirstName descending (-1) ascending would be (1) ...
> db.myCollection.find().sort({ "FirstName" : 1 });
Or using "natural order" ...
Natural order" is defined as the database's native ordering of objects in a collection.
When executing a find() with no parameters, the database returns objects in forward natural order.
So ...
> db.myCollection.sort({$natural:-1})
Ordering by _id should take the datetime that is embedded into the _id (if using a MongoDB ObjectID) into account ...
Upvotes: 3