Add-Ons & Services

MongoDB ObjectId bug?

A general discussion forum.

MongoDB ObjectId bug?

Postby xiaoqingwang » 08 May 2014, 10:52

Poco 1.5.2
win8 64bit

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]);

_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);
std::string sPackedID = ptrObj->toString();
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::SharedPtr<Poco::MongoDB::UpdateRequest> request = db.createUpdateRequest("files");
ObjectId::Ptr ptrObj = MongoDBObjPtrFromString(fileid);//fileid is std::string,but in mongodb is type of ObjectId.
request->selector().add<ObjectId::Ptr>("_id", ptrObj);
Posts: 2
Joined: 08 May 2014, 10:45

Re: MongoDB ObjectId bug?

Postby alex » 09 May 2014, 04:37

Posts: 1113
Joined: 11 Jul 2006, 16:27
Location: United_States

Still in 1.5.3

Postby xiaoqingwang » 17 Jul 2014, 03:22

HI,I have updated poco version 1.5.3,

1、There Still a problem:
I found there was still a problem,when I use 'std::string sUserId = doc->get("_id")->toString(); ',
I got a string which value is '5350e6476d5651c01d006'.

So I think 'MongoDB\include\Poco\MongoDB\ObjectId.h' Line:92
It should be 'const std::string& fmt = "%02x"' instead of 'const std::string& fmt = "%x"',Is that right?
because when I changed ObjectId.h line 92 to "%02x" I got the corrected string '5350e6476d5651c01d000006'

BTW,line:52 : std::string toString(const std::string& fmt = "%02x") const; is fine.

2、How chould I use 'ObjectId::Ptr' ?
Is there any way to get ObjectId::Ptr Like this:ObjectId::Ptr optr = doc->get<ObjectId::Ptr>("_id")->toString(); ?
so that I can use the method 'std::string ObjectId::toString(const std::string& fmt) const' to get string directly.
I am still not familiar with poco yet,I am very appreciated if u chould tell me some advice.

good job,have a nice day. :)
Posts: 2
Joined: 08 May 2014, 10:45

Return to General Discussion

Who is online

Users browsing this forum: No registered users and 1 guest