tobbe
tobbe

Reputation: 1807

get N latest records

How do I get the N latest records with meteors mongodb?

I know I could do it like this with normal mongodb: db.foo.find().sort({_id:1});, so I thought this would work with meteor: collection.find({chatroom: Session.get("room")}, {sort: {_id:1}, limit: N }).

But this only returns some "random" documents. I guess they are the 10 records with the lowest _id value, like _id= aaaaa and _id= aaaab.

What am I missing here? In normal mongodb its supereasy?!

Upvotes: 8

Views: 4014

Answers (2)

Sebastian
Sebastian

Reputation: 2204

I got stuck on limit as well (I reckon it's a Meteor bug). I ended up writing this function:

Template.content.messages = function () {
    var items = Messages.find({}, {sort: {timestamp : 1} }).fetch();
    return items.slice(-15);
}

Timestamp field is defined like this:

timestamp: new Date().getTime()

Upvotes: 4

sohel khalifa
sohel khalifa

Reputation: 5588

Try using $natural sort specifier of mongoDB.

collection.find({chatroom: Session.get("room")}, {sort: {$natural : 1}, limit: N });

The natural order is an order in which the database stores documents on disk. Typically an insertion order.

I use date_created value for sorting normally. Because the natural order changes sometimes, when you perform update operations on existing documents.

Upvotes: 9

Related Questions