2

I have a large mongodb collection where each document represents a simple log message that occurs at at set time interval (say 1 minute). Whenever I do a Find using Mongoose, I get the entire contents of the DB in the order which they were added. I am looking for a query where I can get the last 10 added records without doing a sort on a timestamp. Below is a sample of my of my documents:

[ { _id: 58bd2dcd51d1169260ccbdac,
  contentID: 1,
  clicks: 50,
  views: 61 },
 { _id: 58bd43d40fda0d25b0c6724e,
  'contentID: ': 1,
  clicks: 45,
  views: 72 },
{ _id: 58bd54ae2d67e820143eddda,
  'contentID: ': 1,
  clicks: 25,
  views: 32 }]
Dave S
  • 973
  • 9
  • 17
  • You can sort by ```_id:-1``` but you still need to sort. If you don't sort in 99% of cases you will get rows in natural order. But in 1% they will be randomly ordered. Here is where you can find full explanation http://stackoverflow.com/questions/11599069/how-does-mongodb-sort-records-when-no-sort-order-is-specified – Bonanza Mar 09 '17 at 23:02

1 Answers1

3

Unfortunately I believe you will have to use sort in your query.

example.find()sort.({"_id": -1}).limit(10)

to make it easier, create a variable and then call the variable

var q = db.example.find()sort.({"_id": -1}).limit(10);
q.exec(function() ...},{})
Govna
  • 348
  • 1
  • 4
  • 16
  • If you want to get the last ten records knowing their is a potential they are not the most recent it but are the last ten in the array; use $slice example `db.posts.find( {}, { comments: { $slice: [ -10, 10 ] } } )` this will get you 10 lines of the comments array starting with the 10th from the last item. https://docs.mongodb.com/manual/reference/operator/projection/slice/ – Govna Feb 02 '18 at 18:58