2

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()

Isaac Wasserman
  • 1,461
  • 4
  • 19
  • 39
  • Unless you impose an order on reading with `db.collection.find()` or in an inner document structure, there probably isn't an order. – Paul May 19 '15 at 04:05

2 Answers2

2

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.

saimeunt
  • 22,666
  • 2
  • 56
  • 61
  • 1
    see also http://stackoverflow.com/questions/11599069/how-does-mongodb-sort-records-when-no-sort-order-is-specified – Paul May 19 '15 at 04:03
2

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})
Markus W Mahlberg
  • 19,711
  • 6
  • 65
  • 89