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?!
SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query. mysql> SELECT * FROM ( -> SELECT * FROM Last10RecordsDemo ORDER BY id DESC LIMIT 10 -> )Var1 -> -> ORDER BY id ASC; The following is the output that displays the last 10 records.
Latest record of all column: The data that we get on the top of the table is our latest data, we will use OrderBy Descending to get our record.
1 Answer. ORDER BY id ASC; In the above query, we used subquery with the TOP clause that returns the table with the last 5 records sorted by ID in descending order. Again, we used to order by clause to sort the result-set of the subquery in ascending order by the ID column.
The TOP clause in SQL Server returns the first N number of records or rows from a table. Applying the ORDER BY clause with DESC, will return rows in descending order. Hence, we get the last 3 rows.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With