Reputation: 3447
I have some huge collection of records resent in my mongodb This is the sample
db.logins.find().pretty()
"cust_id" : "testuser",
"error" : "no error"
"cust_id" : "testuser",
"error" : "unable to connect"
"cust_id" : "sam",
"error" : "no error"
"cust_id" : "sdert",
"error" : "unable to connect"
When i do db.logins.find().pretty()
it displays records of the past (old ones)
I need to execute the command it
contnously to see them
My question is , how can i see the latest records initially when i do db.logins.find().pretty()
??
Upvotes: 0
Views: 64
Reputation: 5902
You can use sort. That is if you have a field that contains a date object you can use it to sort the results. That is,
db.logins.find().sort({date_field: -1}).pretty()
-1
signifies that the records will be sorted in descending order.
If it is of any help, you can try sorting by natural order
db.logins.find().sort({$natural: -1}).pretty()
This however does not guarantee that sorted results will match the insertion order. Sorting on a date field will still be better.
Upvotes: 3
Reputation: 42342
You can use the _id field that MongoDB generates for you - the first four bytes are the timestamp so sorting on it descending will give you reverse insertion order.
The difference between using _id and $natural is the latter gives them in disk order, and there may not be a guarantee that your records have been written contiguously on disk where ascending order of _id field is guaranteed.
db.logins.find().sort({_id:-1})
In addition, the _id has an index on it, sort it's used for sort to avoid the performance hit sorting would otherwise take.
Upvotes: 0
Reputation: 43884
You can use $natural here as well, which will give mostly the same effect (not totally due to distributed environments):
http://docs.mongodb.org/manual/reference/operator/natural/
db.logins.find().sort({$natural:-1})
Upvotes: 0