开发者

Ordering by query

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:

d开发者_如何转开发b.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).


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 ...


also can do like this

db.things.find({_id:{$in: [4,2,6]}}).sort({_id:1});

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜