【问题标题】:How do I extract the created date out of a Mongo ObjectID如何从 Mongo ObjectID 中提取创建日期
【发布时间】:2011-11-11 17:46:57
【问题描述】:

我正在使用 Mongo shell 来查询我的 Mongo 数据库。我想使用 ObjectID 中包含的时间戳作为我的查询的一部分,也作为一列提取到输出中。我已经设置 Mongo 自己创建 ObjectID。

我的问题是我不知道如何使用 ObjectID 来提取其时间戳。

以下是我正在尝试解决的问题。 “createdDate”字段是占位符;不确定正确的字段是什么:

//Find everything created since 1/1/2011
db.myCollection.find({date: {$gt: new Date(2011,1,1)}});

//Find everything and return their createdDates
db.myCollection.find({},{createdDate:1});

【问题讨论】:

    标签: shell mongodb timestamp unix-timestamp


    【解决方案1】:

    getTimestamp()

    你需要的功能就是这个,它已经包含在你的shell中了:

    ObjectId.prototype.getTimestamp = function() {
        return new Date(parseInt(this.toString().slice(0,8), 16)*1000);
    }
    

    参考文献

    从文档中查看此部分:

    此单元测试也演示了相同的内容:

    使用 Mongo shell 的示例:

    > db.col.insert( { name: "Foo" } );
    > var doc = db.col.findOne( { name: "Foo" } );
    > var timestamp = doc._id.getTimestamp();
    
    > print(timestamp);
    Wed Sep 07 2011 18:37:37 GMT+1000 (AUS Eastern Standard Time)
    
    > printjson(timestamp);
    ISODate("2011-09-07T08:37:37Z")
    

    【讨论】:

    • 你有一个如何从shell调用这个函数的例子吗?我尝试了类似 _id.getTimestamp() 的方法,但 Mongo 并不喜欢它。谢谢。
    • 这对我检索数据后很有帮助,但我仍然不知道如何将创建的日期用作查询参数。例如。 '给我所有在 2011 年 1 月 1 日之后创建的小部件'。也许我错过了什么?
    • 仅供参考-您也可以在一行中完成:> ObjectId().getTimestamp() ISODate("2011-09-07T16:17:10Z")
    • 事实证明您无法查询 ObjectId 中的日期。所以我要添加我自己的时间戳列。使用 ObjectId 中的内置时间戳会很好。感谢您在结果集上查询它的所有帮助!
    • @yourfriendzak 方法调用getTimestamp() docs.mongodb.org/manual/reference/method/ObjectId.getTimestamp/…
    【解决方案2】:

    This question 有助于了解如何在查询情况下使用 _id 的嵌入时间戳(参考Mongo Extended JSON 文档)。这样做是这样的:

    col.find({..., 
         '_id' : {'$lt' : {'$oid' : '50314b8e9bcf000000000000'}} 
    })
    

    查找早于 oid 给出的文档创建的文档。与自然排序和限制一起使用,您可以利用 BSON _ids 来创建类似 Twitter 的 API 查询(给我你拥有的最后一个 OID,我会再提供 20 个

    【讨论】:

    • 您的答案实际上可以在 mongo 查询中使用。谢谢!
    • 这只适用于 mongoexport 命令: mongoexport -d twitter -c tweets -q '{"_id" : {"$gte" : {"$oid" : " 50e54ec00000000000000000"}}}' 我无法使用 mongo shell 得到任何结果: db.tweets.find({"_id" : {"$gte" : {"$oid" : " 50e54ec00000000000000000"}}})
    • 设法让它在 Mongo shell 中工作:db.tweets.find({ "_id" : { $gte : ObjectId("50d314e40000000000000000") } }) 并使用 C++ MongoDB 驱动程序和以下查询:std::string qs = "{ \"_id\" : { $gte : { \"$oid\" : \"" + oid + "\" } } }"; std::auto_ptr<mongo::DBClientCursor> cursor = c.query("twitter.tweets", mongo::Query(qs));
    【解决方案3】:

    在python中你可以这样做:

    >>> from bson.objectid import ObjectId
    >>> gen_time = datetime.datetime(2010, 1, 1)
    >>> dummy_id = ObjectId.from_datetime(gen_time)
    >>> result = collection.find({"_id": {"$lt": dummy_id}})
    

    我认为,ObjectId.from_datetime() - 它是标准 bson 库的有用方法 也许其他语言绑定具有替代的内置功能。 来源:http://api.mongodb.org/python/current/api/bson/objectid.html

    【讨论】:

    • 或者,换一种说法:好的答案伴随着代码示例,并为未来的读者提供解释。虽然问这个问题的人可能理解你的答案,但解释你是如何得出这个问题的可能会帮助无数其他人。
    • 对不起,我想我错过了主题并回答了另一个问题
    【解决方案4】:

    要使用 ObjectId 中包含的时间戳并返回某个日期之后创建的文档,您可以将$where 与函数一起使用。

    例如

    db.yourcollection.find( { 
      $where: function() { 
        return this._id.getTimestamp() > new Date("2020-10-01")
      } 
    });
    

    该函数需要为该文档返回一个真实值以包含在结果中。参考:$where

    Mongo 日期对象看起来有点奇怪。有关构造函数的详细信息,请参阅 mongo Date() documentation

    摘录:

    You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats:
    
        new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
        new Date("<YYYY-mm-ddTHH:MM:ss>") specifies the datetime in the client’s local timezone and returns the ISODate with the specified datetime in UTC.
        new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
        new Date(<integer>) specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance.
    
    

    【讨论】:

      猜你喜欢
      • 2013-07-12
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2012-11-15
      • 2014-11-09
      • 2016-08-28
      相关资源
      最近更新 更多