C++生成Mongo object ID

来源:互联网 发布:idc服务器托管数据安全 编辑:程序博客网 时间:2024/05/16 16:06

最近做一个项目要用到mongo db,需要使用C++语言生成id,以使几个collection的数据关联起来。经过这段时间的学习,算是有点入门了,终于用C++生成了ID。


Mongo ID 简述

In MongoDB, documents stored in a collection require a unique_id field that acts as aprimary key. BecauseObjectIds are small, most likely unique, and fast to generate, MongoDB uses ObjectIds as the default value for the_id field if the_id field is not specified. MongoDB clients should add an_idfield with a unique ObjectId. However, if a client does not add an_id field,mongod will add an_id field that holdsan ObjectId.


ObjectId is a 12-byteBSON type,constructed using:

  • a 4-byte value representing the seconds since the Unix epoch,
  • a 3-byte machine identifier,
  • a 2-byte process id, and
  • a 3-byte counter, starting with a random value.

Using ObjectIds for the _id field provides the followingadditional benefits:

  • in the mongo shell, you can access the creation time oftheObjectId, using thegetTimestamp() method.

  • sorting on an _id field that storesObjectId values isroughly equivalent to sorting by creation time.

官网地址:http://docs.mongodb.org/manual/reference/object-id/

大概意思就是说:

存储在mongo collection(相当于表)中的每一个document(记录)都有唯一的字段_id,并且在它的值在整个collection是唯一的。如果在插入数据时,不指定它,Mongodb将自动为这条记录添加这个字段,并且以ObjectId作为它的默认类型。 

ObjectId 是由12字组成。

1. 日历时间,从epoch时间经过的秒数。

2. 机器标识。

3. 进程ID

4. 一个随机值。

可以说,ObjectId是全球唯一的,你可以把它认识是Linux 上的UUID(在Windows 上被称为GUID)。mongdb这样做是为了支持分布式,以唯一的标识一条数据。


C++生成ID

运行环境:cento OS 6.4

编程语言:C++

mongo C++驱动版本:2.4

代码如下:

void mongo_objectid (){        BSONObjBuilder b;        // generate a id         b.genOID ();        BSONObj p = b.obj();        BSONElement e;        if (p.getObjectID (e))        {            mongo::OID myid = e.__oid ();            cout << "my id is : " << myid.toString () << endl;        }        else        {            cout << "failed to get id\n" << endl;        }}

主要用到了以下几个类:

BSONObj:mongo是文档(document)型数据库,一个document相当于关系数据库表中的一条记录。即一个BSONObj就相当于关系数据库中的一条记录。

BSONElement:在关系数据库中,一张表中有多个字段。因此,一个BSONElement可以看作是表中的一个字段。BSONObj类提供了接口,通过字段名,获取它的值,即一个存储字段对应的值的BSONElement对象。

mongo::OID:在Mongo C++ API中封装了此类,用于表示ID,此类提供了一系列的接口,转换成不同的格式。

BSONObjBuilder:此类对于构造BSONObj。


代码步骤:

1. 调用BSONObjBuilder::genOID() ,生成一个含有ID的BSONObj对象

2. 调用BSONObjBuilder::obj ()获取 BSONObj对象。

3. 调用接口bool     BSONObj::getObjectID (BSONElement &e) const 获取ID,并保存在BSONElement类型的对象中。

4. 调用const mongo::OID &     BSONElement::__oid () const接口,获取ID。mongo C++驱动中,用mongo::OID表示一个ID对象,它提供了相应的接口,转换成不同的格式。



0 0