I'm building a meteor social network type app and it needs to insert documents at the top of a collection instead of the bottom. How can I do this? It would have to be like the JS unshift()
You shouldn't rely on MongoDB documents "natural" order because it's unpredictable (documents may be moved anytime by the MongoDB engine).
Add another field dedicated to sorting in your collection schema, such as a createdAt
of type Date
or an order
of type Number
, and when displaying your documents, use a Mongo sort
clause.
There's an overhead trying to maintain coherency among your order
field though.
There is no such thing as the "top" of a collection, except for in capped collection's .
What you have to do is to sort your collection according to the field when doing your query.
So for example documents inserted like this
db.enemies.insert({ name: "Zod"})
db.enemies.insert({ name: "Lex Luthor"})
would be returned in a proper alphabetical order when queried like this
db.enemies.find({}).sort({name:1})
For large collections, you want to create a compound index over your search criteria and sort criteria (order matters!) to speed things up
db.collection.ensureIndex({queryField1:1, queryField2:1, sortField1:1, sortField2:-1})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.