我想为要作为新插入的文档生成 mongo objectid,并覆盖时间戳值。所以我使用下面的代码来获取objectid。
var oIdWithTimestamp = function (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 = mongoose.Types.ObjectId(hexSeconds + "0000000000000000");
return constructedObjectId
};
但是如果我想插入两个具有相同时间戳的文档,它不能满足需要。我注意到有一个 get_inc 函数用于向 objectid 添加增量值。并且可以使用相同的时间戳生成 16777214 个不同的 objectid。任何有关如何使用此增量器获取最大 16777214 的唯一时间戳的帮助都将受到赞赏。
最佳答案
我尝试使用下面的代码片段生成随机 mongo objectid。
var bson = require('bson');
var generateObjIdFromTime = function(spefictime) {
spefictime = ~~(spefictime/1000);
return bson.ObjectID(spefictime);
}
它生成具有给定时间戳的随机 mongo objectid。
关于mongodb - 根据具有唯一增量的时间戳构造 Mongo ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47307772/