S
S
source20032016-12-08 00:34:33
MongoDB
source2003, 2016-12-08 00:34:33

How to find the latest documents in a collection with a where condition?

There is a collection of several million documents, each entry has a date: timestamp, you need to display the latest entries, where date: timestamp > current timestamp - 5, i.e. records for the last 5 seconds. They are expected in the response somewhere from 0 to 300.
I tried to use the $where function, but the response takes a very long time, as far as I understand, this is a resource-intensive operation.
Please tell me the best way to make this request.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Shatokhin, 2016-12-08
@source2003

It is desirable to add an index to this field.

collection.find({
  'date': {
    $gte: new Date(Date.now() - 5000) // 5000ms = 5 секунд
  }
});

If this field is of type Integer, and not Date, then there is no need to wrap it in new Date.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question