How to fetch a document from MongoDB inserted only within last few minutes?

Viewed 69

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.

1 Answers

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 });
Related