Get the latest 50 documents with .find() in mongodb (monk)

142 views Asked by At

I am trying to get the latest 50 documents with the line

const msgs = await messages.find({ 'group': this.id }, { limit: 50 })

but this only gets the oldest 50 documents instead of the latest ones

Any way i can solve this?

1

There are 1 answers

0
Jakub A Suplicki On

You are missing the line which would indicate the timeframe of your document being created like sort: {'createdAt': 'desc'}.

This will allow you to get only the latest 50 documents based on the date (should be a type of Date) when they were created.

Otherwise, you would need to use some other property which would indicate the order of your documents being created (id is usually random value so sorting with it would not work as expected).


messages.find({ 'group': this.id })
.sort({'createdAt': 'desc'})
.limit(50)
.then(msgs => {
  console.log(msgs)
});

const msgs = await messages.find({ 'group': this.id }, { sort: {'createdAt': 'desc' }, limit: 50 })