2

I am using the below query to fetch the latest document.

const user = await Conversation.find({ isBot: false, to: from.slice(9), queryType: "template_preview" }).sort({ sentTime: -1 }).limit(1);

But the issue is this can also fetch old documents inserted long before. But for my use case I want the document inserted before few minutes say 5 min. What should be the exact query for this.

prasad_
  • 12,755
  • 2
  • 24
  • 36
Sachin Singh
  • 87
  • 1
  • 1
  • 9
  • A better approach would be to store timestamp and query documents based upon that. In case, the _id field is of type [ObjectId](https://docs.mongodb.com/manual/reference/method/ObjectId/index.html), you can extract the timestamp from ObjectId and query on that too. – prasad_ Feb 25 '21 at 05:43
  • I have stored timestamp in my model. I got your point but I am new to this can you share the exact to check query for last 5 min – Sachin Singh Feb 25 '21 at 06:12
  • See these posts [Date query with ISODate in mongodb doesn't seem to work](https://stackoverflow.com/questions/19819870/date-query-with-isodate-in-mongodb-doesnt-seem-to-work/19820260) and [Between dates query in MongoDB](https://stackoverflow.com/questions/28617784/between-dates-query-in-mongodb). – prasad_ Feb 25 '21 at 06:15

1 Answers1

0

Try this one:

const user = await Conversation.find({ 
         isBot:false,
         sendTime:{
            $gte: timestamp of -5 min,
            $lte: timestamp (now)
         },
         queryType: "template_preview"
     }).sort({ sentTime: -1 });