Isaac Wasserman
Isaac Wasserman

Reputation: 1541

Add to top of collection meteor

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

Upvotes: 2

Views: 160

Answers (2)

Markus W Mahlberg
Markus W Mahlberg

Reputation: 20703

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

Upvotes: 2

saimeunt
saimeunt

Reputation: 22696

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.

Upvotes: 2

Related Questions