MongoDB C++ Driver mongocxx-3.11.0
Loading...
Searching...
No Matches
ObjectID

Table of Contents

How to use ObjectID (OID) interfaces.

Basic Usage

void example() {
{
ASSERT(a != b); // Random and unique per process.
}
{
char bytes[bsoncxx::oid::k_oid_length]{};
bsoncxx::oid oid{bytes, sizeof(bytes)};
{
std::time_t time = oid.get_time_t();
char str[sizeof("YYYY-MM-DD HH:MM:SS")];
ASSERT(std::strftime(str, sizeof(str), "%F %T", std::gmtime(&time)) ==
sizeof(str) - 1u);
ASSERT(std::string(str) == "1970-01-01 00:00:00");
}
ASSERT(oid.bytes() != bytes); // Seperate storage.
ASSERT(oid.size() == bsoncxx::oid::k_oid_length);
ASSERT(std::memcmp(bytes, oid.bytes(), oid.size()) == 0);
ASSERT(oid.to_string() == "000000000000000000000000");
ASSERT(oid == bsoncxx::oid{"000000000000000000000000"});
}
{
// Timestamp: 946771199 (0x386e94ff)
// Value: 286462997 (0x11131415)
// Counter: 2171427 (0x212223)
bsoncxx::oid oid{"386e94ff1112131415212223"};
{
std::time_t time = oid.get_time_t();
char str[sizeof("YYYY-MM-DD HH:MM:SS")];
ASSERT(std::strftime(str, sizeof(str), "%F %T", std::gmtime(&time)) ==
sizeof(str) - 1u);
ASSERT(std::string(str) == "2000-01-01 23:59:59");
}
ASSERT(oid < bsoncxx::oid{"389622001112131415212223"}); // Timestamp: 2000-02-01 00:00:00
ASSERT(oid > bsoncxx::oid{"386d43801112131415212223"}); // Timestamp: 2000-01-01 00:00:00
ASSERT(oid < bsoncxx::oid{"386e94ffffffffffff212223"}); // Value: 1099511627775
ASSERT(oid > bsoncxx::oid{"386e94ff0000000000212223"}); // Value: 0
ASSERT(oid < bsoncxx::oid{"386e94ff1112131415ffffff"}); // Counter: 16777215
ASSERT(oid > bsoncxx::oid{"386e94ff1112131415000000"}); // Counter: 0
}
}

Error Handling

void example() {
try {
bsoncxx::oid oid{"invalid"}; // Throws.
ASSERT(false && "should not reach this point");
} catch (const bsoncxx::exception& ex) {
ASSERT(ex.code() == bsoncxx::error_code::k_invalid_oid);
}
try {
char bytes[1]{};
bsoncxx::oid oid{bytes, sizeof(bytes)}; // Throws.
ASSERT(false && "should not reach this point");
} catch (const bsoncxx::exception& ex) {
ASSERT(ex.code() == bsoncxx::error_code::k_invalid_oid);
}
}