Mongodb 从 ObjectId 获取 3 字节计数器 [英] Mongodb get the 3-byte counter from an ObjectId

查看:47
本文介绍了Mongodb 从 ObjectId 获取 3 字节计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何/我可以得到

3 字节计数器,从一个随机值开始

3-byte counter, starting with a random value

来自 mongodb ObjectId 的一部分?

part from a mongodb ObjectId?

我有一个这样的 ObjectId:ObjectId("507f1f77bcf86cd799439011")

I have an ObjectId like this: ObjectId("507f1f77bcf86cd799439011")

根据 mongodb 文档:

According to mongodb documentation:

说明

ObjectId() 返回一个新的 ObjectId 值.12 字节ObjectId 值包括:

ObjectId() Returns a new ObjectId value. The 12-byte ObjectId value consists of:

一个 4 字节的值,表示自 Unix 纪元以来的秒数,

a 4-byte value representing the seconds since the Unix epoch,

一个 3 字节的机器标识符,

a 3-byte machine identifier,

一个 2 字节的进程 ID,

a 2-byte process id,

和一个 3 字节的计数器,从一个随机值开始.

我想得到和一个 3 字节的计数器,从一个随机值开始.";如果可能,请从上面的 ObjectId 部分删除.

I want to get the "and a 3-byte counter, starting with a random value." part from the ObjectId above if its possible.

推荐答案

您可以尝试以下技巧,在那里您可以获得 ObjectId 使用 toString()toHexString(),使用 parseIntslice 来获取部分.因为十六进制数字是一个字节的一半,所以偏移量是原来的两倍:

You could try the following hack where you can get the equivalent string representation of the ObjectId using toString() or toHexString(), use parseInt and slice to get the parts. Because hex digits are half of a byte the offsets are twice as much:

db.collection("collectionName").findOne({}, function(err, result) {     
    if (result) {
        var id          = result._id.toString(), ctr = 0;
        var timestamp   = parseInt(id.slice(ctr, (ctr+=8)), 16);
        var machineID   = parseInt(id.slice(ctr, (ctr+=6)), 16);
        var processID   = parseInt(id.slice(ctr, (ctr+=4)), 16);
        var counter     = parseInt(id.slice(ctr, (ctr+=6)), 16);
        console.log(id);
        console.log(timestamp);
        console.log(machineID);
        console.log(processID);
        console.log(counter);                    
    }       
});

这篇关于Mongodb 从 ObjectId 获取 3 字节计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆