MongoDB: Only fetch documents created in the last 24hrs?

后端 未结 7 2049
遇见更好的自我
遇见更好的自我 2020-12-03 04:41

I want to limit a query I\'m making to only look in documents that were created in the past 24 hrs.

What is the best way to structure this query? How do I go about

7条回答
  •  臣服心动
    2020-12-03 05:06

    If you're not using any other indexes and are using the default ObjectID as your _id, you can do the following:

    var ObjectID = require('mongodb').ObjectID
    
    db.collection.find({
      _id: {
        $gt: ObjectID.createFromTime(Date.now() / 1000 - 24*60*60)
      }
    }, callback)
    

提交回复
热议问题