H
H
HellishCode2020-12-21 13:14:45
MongoDB
HellishCode, 2020-12-21 13:14:45

How to search in MongoDB by indexes?

Good afternoon
When creating a collection, I create an index

await this.db.collection('users').insertOne({
        id: id,
        user_id: userId,
        sent_at: new Date(),
      });

 await this.db.collection('throttling_pitch_queue').createIndex({
        sent_at: Date.now(), // можно ли как-то использовать new Date() для индексов?
      });

Next, I'm looking for users who were added within a minute
const user = database
              .collection('users')
              .find({
                sent_at: {
                  $gt: new Date(new Date().getTime() - 60000),
                },
              })
              .toArray();

Questions:
  1. When creating an index, for sent_at, can I somehow use new Date() , now I have an error, because it says that this format cannot exist?
  2. Now my search is on the sent_at field, if I'm not mistaken, then the search on the index will be much faster, especially if there can be a million users. Please tell me how to search by the set_at index in this case using the same algorithm as now: new Date(new Date().getTime() - 60000), ?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question