用于 mongodb ObjectId 创建时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5125521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 11:59:32  来源:igfitidea点击:

uses for mongodb ObjectId creation time

mongodbtimestampunix-timestamp

提问by kefeizhou

The ObjectIdused as the default key in mongodb documents has embedded timestamp (calling objectid.generation_time returns a datetime object). So it is possible to use this generation time instead of keeping a separate creation timestamp? How will you be able to sort by creation time or query for the last N items efficiently using this embedded timestamp?

ObjectId用作MongoDB的文档的默认密钥嵌入时间戳(调用objectid.generation_time返回datetime对象)。那么可以使用这个生成时间而不是单独保留一个创建时间戳吗?您将如何使用此嵌入式时间戳有效地按创建时间排序或查询最后 N 个项目?

回答by Andrew Orsich

I suppose since MongoDB ObjectId contain a timestamp, you can sort by 'created date' if you will sort by objectId:

我想由于 MongoDB ObjectId 包含一个时间戳,如果您按 objectId 排序,则可以按“创建日期”排序:

items.find.sort( [['_id', -1]] ) // get all items desc by created date.

And if you want last 30 created items you can use following query:

如果您想要最后 30 个创建的项目,您可以使用以下查询:

items.find.sort( [['_id', -1]] ).limit(30) // get last 30 createad items 

I am actualy not sure,i just suppose that ordering by _id should work as described above. I'll create some tests later.

我实际上不确定,我只是假设按 _id 排序应该按上述方式工作。稍后我将创建一些测试。

Update:

更新:

Yes it is so. If you order by _id you will automatically order by _id created date. I've done small test in c#, mb someone interest in it:

是的,确实如此。如果您按 _id 订购,您将自动按 _id 创建日期订购。我在 c# 中做了一个小测试,mb 有人对它感兴趣:

  public class Item
  {
    [BsonId]
    public ObjectId Id { get; set; }

    public DateTime CreatedDate { get; set; }

    public int Index { get; set; }
  }



 [TestMethod]
 public void IdSortingTest()
 {
   var server = MongoServer.Create("mongodb://localhost:27020");
   var database = server.GetDatabase("tesdb");

   var collection = database.GetCollection("idSortTest");
   collection.RemoveAll();

   for (int i = 0; i <= 500; i++)
   {
     collection.Insert(new Item() { 
             Id = ObjectId.GenerateNewId(), 
             CreatedDate = DateTime.Now, 
             Index = i });
   }

   var cursor = collection.FindAllAs<Item>();
   cursor.SetSortOrder(SortBy.Descending("_id"));
   var itemsOrderedById = cursor.ToList();

   var cursor2 = collection.FindAllAs<Item>();
   cursor2.SetSortOrder(SortBy.Descending("CreatedDate"));
   var itemsOrderedCreatedDate = cursor.ToList();

   for (int i = 0; i <= 500; i++)
   {
     Assert.AreEqual(itemsOrderedById[i].Index, itemsOrderedCreatedDate[i].Index);
   }
}

回答by user105991

Yes, you can use the generation_time of BSON ObjectId for the purposes you want. So,

是的,您可以将 BSON ObjectId 的 generation_time 用于您想要的目的。所以,

db.collection.find().sort({ _id : -1 }).limit(10)

will return the last 10 created items. However, since the embedded timestamps have a one second precision, multiple items within any second are stored in the order of their creation.

将返回最近创建的 10 个项目。但是,由于嵌入的时间戳具有一秒的精度,因此任何一秒内的多个项目都按其创建顺序存储。

回答by DanH

The code to convert a DateTime to its corresponding timestamp with the c# driver is as follows:

使用 c# 驱动程序将 DateTime 转换为其对应时间戳的代码如下:

    public static ObjectId ToObjectId(this DateTime dateTime)
    {
        var timestamp = (int)(dateTime - BsonConstants.UnixEpoch).TotalSeconds;
        return new ObjectId(timestamp, 0, 0, 0);
    }

More info here: http://www.danharman.net/2011/10/26/mongodb-ninjitsu-using-objectid-as-a-timestamp/

更多信息:http: //www.danharman.net/2011/10/26/mongodb-ninjitsu-using-objectid-as-a-timestamp/

回答by wprl

From: http://www.mongodb.org/display/DOCS/Object+IDs#ObjectIDs-DocumentTimestamps

来自:http: //www.mongodb.org/display/DOCS/Object+IDs#ObjectIDs-DocumentTimestamps

"sorting on an _id field that stores ObjectId values is roughly equivalent to sorting by creation time, although this relationship is not strict with ObjectId values generated on multiple systems within a single second."

“对存储 ObjectId 值的 _id 字段进行排序大致相当于按创建时间排序,尽管这种关系对于一秒钟内在多个系统上生成的 ObjectId 值并不严格。”

回答by Chen Dachao

To query projects created within 7 days, I use below snippet:

要查询在 7 天内创建的项目,我使用以下代码段:

db.getCollection('projects').find({
  $where: function() {
    // last 7 days
    return Date.now() - this._id.getTimestamp() < (7 * 24 * 60 * 60 * 1000)
  }
}).sort({
  '_id': -1
})

and if you want to get items with specified fields:

如果您想获取具有指定字段的项目:

db.getCollection('projects').find({
  $where: function() {
    // last 7 days
    return Date.now() - this._id.getTimestamp() < (7 * 24 * 60 * 60 * 1000)
  }
}).sort({
  '_id': -1
}).toArray().map(function(item) {
  var res = {};
  res['Project Name'] = item.config.label;
  res['Author'] = item.author;
  res['Created At'] = item._id.getTimestamp().toLocaleDateString();
  res['Last Modified Date'] = item.config.lastModifDate.toLocaleString();
  return res;
});

it will return something like this:

它将返回如下内容:

[{
  "Project Name": "Newsletter",
  "Author": "larry.chen",
  "Created At": "Thursday, January 19, 2017",
  "Last Modified Date": "Thursday, January 19, 2017 17:05:40"
}...]

PS:the software I use to connect to MongoDB is Robo 3T

PS:我用来连接MongoDB的软件是Robo 3T

Hope this will help you.

希望这会帮助你。

回答by Andreas Jung

See

http://www.mongodb.org/display/DOCS/Object+IDs#ObjectIDs-DocumentTimestamps

http://www.mongodb.org/display/DOCS/Object+IDs#ObjectIDs-DocumentTimestamps

Likely doable however I would always prefer having a dedicated timestamp instead of relying on some such internals like timestamp somehow embedded in some object id.

可能可行,但是我总是更喜欢有一个专用的时间戳,而不是依赖某些内部结构,例如以某种方式嵌入某些对象 ID 中的时间戳。