mongodb limit operation retrieve newest docs -


mongodb find return docs ascending order of "_id", when apply limit(n) on find(), return oldest n docs (assume doc1's _id > doc2's _id imply doc1 newer doc2, example, objectid ). want let return newest n docs do:

col.find().sort({"_id":-1}).limit(n) 

is inefficient? mongodb sort docs in 'col'?

the _id field "primary key" , therefore has index there not "sort" on whole collection, traverses primary index in reverse order in case.

provided happy enough reflect "newest" documents, , in normal circumstances there no reason believe otherwise, return want in efficient manner.

if indeed want sort else such timestamp or other field create index on field , sort have above. general cases should use index , return in "descending order" or specified in direction of sort or default index

db.collection.ensureindex({ "created": 1 }) 

or default "descending" :

db.collection.ensureindex({ "created": -1 }) 

then query:

db.collection.find().sort({ "created": -1 }) 

so not "sort" whole collection when index present use. _id key indexed.

also see .ensureindex() in documentation.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -