Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a MongoDB objectid contain only numbers?

Can a MongoDB objectid contain only numbers?

There is a piece of code in a library that i'm using that does the following:

if (is_int($mixed) || ctype_digit($mixed)) {
    return;
}

And as a result it is throwing away a record in my DB with an ObjectId of '512417805115179054000022' because it only contains numbers.

Every other record has an ObjectId containing at least one alpha char such as '51241740511517a25b000017'

Is this a problem with the function that it assumes an ObjectId can never contain only numbers when it is in fact possible, or is it some lower level issue with a driver or something that has created an ObjectId with only numeric chars in error?

like image 792
user698883 Avatar asked Oct 24 '25 15:10

user698883


2 Answers

The regular expression used inside MongoDB to validate object ID's is /^[0-9a-fA-F]{24}$/

That means, an object ID can contain both numbers from 0-9 and uppercase or lowercase letters from a-f. And the ID will always have 24 characters. So an object ID with only numbers is as much possible as an object ID with only letters.

like image 174
Sparky Avatar answered Oct 27 '25 03:10

Sparky


The ObjectId is BSON and you are seeing the HEXADecimal representation. So yes it is correct to assume that some IDs will not have letters.

like image 43
gfelisberto Avatar answered Oct 27 '25 04:10

gfelisberto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!