Skip to content

MongoDB ObjectId string formatting #440

@aleks-f

Description

@aleks-f

from http://pocoproject.org/forum/viewtopic.php?f=10&t=6180

Post by xiaoqingwang » Thu May 08, 2014 3:52 am

Platform:
Poco 1.5.2
win8 64bit
VS2013

1、MongoDB ObjectId to String (is this a bug?)
MongoDB\src\ObjectId.cpp:line 63:

s += format("%x", (unsigned int) _id[i]);
should be:
s += format("%02x", (unsigned int) _id[i]);

eg:
_id[0] = 0x53
_id[1] = 0x6a
_id[2] = 0xee
_id[3] = 0xbb
_id[4] = 0xa0
_id[5] = 0x81
_id[6] =0xde
_id[7] =0x68
_id[8] = 0x15
_id[9] = 0x00
_id[10] = 0x00
_id[11] = 0x02

when call ObjectId::toString():
it will get a string:536aeebba081de6815002
but I want it to be:536aeebba081de6815000002

2、I want a method like this :ObjectId::fromString(const std::string &sID)
now I have to do like this:

include "Poco/MongoDB/ObjectId.h"

include "Poco/BinaryReader.h"

include <boost/algorithm/hex.hpp>

ObjectId::Ptr MongoDBObjPtrFromString(const std::string& sID)
{
ObjectId::Ptr ptrObj(new ObjectId);
std::string sHex = boost::algorithm::unhex(sID);
std::istringstream istr(sHex);
Poco::BinaryReader reader(istr, Poco::BinaryReader::LITTLE_ENDIAN_BYTE_ORDER);
BSONReader(reader).readObjectId::Ptr(ptrObj);
std::string sPackedID = ptrObj->toString();
BOOST_ASSERT(sPackedID == sID);
return ptrObj;
}

consider this scene:
query record according to id(ObjectId):
I chould not find a sample like this.so I have to do it as following:
Poco::MongoDB::Database db(sDBName
);
Poco::SharedPtrPoco::MongoDB::UpdateRequest request = db.createUpdateRequest("files");
ObjectId::Ptr ptrObj = MongoDBObjPtrFromString(fileid);//fileid is std::string,but in mongodb is type of ObjectId.
request->selector().addObjectId::Ptr("_id", ptrObj);
...

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions