【问题标题】:Query to get data from mongodb using ObjectId ("xxxxxxxxx").GetTimestamp()使用 ObjectId ("xxxxxxxxx").GetTimestamp() 查询从 mongodb 获取数据
【发布时间】:2021-05-09 00:20:53
【问题描述】:

我从 mongodb 的世界开始。

我有以下问题:

我想查找从日期 x 发布的项目。在记录中我没有日期,但我可以从这个声明中得到它:

ObjectId ("5ffdc390fdd1596ca5870bec"). GetTimestamp ()

其结果是:ISODate ("2021-01-12T15: 43: 12Z")

如何创建一个查询来返回从给定日期(例如从 2021 年 1 月 12 日开始)创建的所有记录? 非常感谢!

【问题讨论】:

  • 这能回答你的问题吗? Can I query MongoDB ObjectId by date?
  • 不,我只使用 mongodb 而不是应用程序。我只需要一个 mongodb 查询
  • 我找到了一个替代解决方案,它与使用定义日期创建的 oid 进行比较以比较 db.getCollection("files").find({"_id" : { $lte :ObjectId( "6018c03000000000000000000") }}) 它有效,但不是最终解决方案

标签: mongodb mongodb-query robo3t


【解决方案1】:

mongo Shell 是 MongoDB 的交互式 JavaScript 接口,因此 Leftium 的解决方案应该可以工作。

function objectIdWithTimestamp(timestamp) {
    /* Convert string date to Date object (otherwise assume timestamp is a date) */
    if (typeof(timestamp) == 'string') {
        timestamp = new Date(timestamp);
    }

    /* Convert date object to hex seconds since Unix epoch */
    var hexSeconds = Math.floor(timestamp/1000).toString(16);

    /* Create an ObjectId with that hex timestamp */
    var constructedObjectId = new ObjectId(hexSeconds + "0000000000000000");

    return constructedObjectId
}


/* Find all documents created between Jan 12th, 2021 and Jan 13th, 2021 */
db.mycollection.find({ _id: { $gt: objectIdWithTimestamp('2021/01/12'), $lt: objectIdWithTimestamp('2021/01/13')  } }); 

【讨论】:

    【解决方案2】:

    可以直接查询:

    db.collection.find({
      $expr: { 
         $gte: [ {$toDate: "$_id"}, ISODate("2021-01-01T00:00:00Z") ] }
      }
    )
    

    通常我更喜欢moment.js 库,例如:

    db.collection.find({
      $expr: { 
         $gte: [ {$toDate: "$_id"}, moment().startOf('day').subtract(3, 'days').toDate() ] }
      }
    )
    

    【讨论】:

    • 它对我不起作用:db.fs.files.find({_id: {$lte: ISODate("2020-02-01T00:00:00+01:00")} }) --Fetched 0 record(s) in 27ms 但是会显示很多记录: db.getCollection("fs.files").count({"_id" : { $lte :ObjectId("6018c0300000000000000000") }}) --631 ObjectId("6018c0300000000000000000").getTimestamp() ---ISODate("2021-02-02T03:00:00Z")
    • 更新我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多