Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for MongoDB ObjectID

With reference to this SO question, I have a scenario where I only need to match a hex string with a-f included. All else should not match. Example:

checkForHexRegExp.test("112345679065574883030833"); // => false checkForHexRegExp.test("FFFFFFFFFFFFFFFFFFFFFFFF"); // => false checkForHexRegExp.test("45cbc4a0e4123f6920000002"); // => true 

My use case is that I am working with a set of hex strings and would like to only validate as true those that are mongodb objectIDs.

like image 982
gmajivu Avatar asked Jan 08 '14 06:01

gmajivu


People also ask

What is the type of ObjectId in MongoDB?

Every document in the collection has an “_id” field that is used to uniquely identify the document in a particular collection it acts as the primary key for the documents in the collection. “_id” field can be used in any format and the default format is ObjectId of the document.

How an ObjectId type is composed in MongoDB?

An ObjectId in MongoDB is a 12-byte BSON type. In the 12-byte structure, the first 4 bytes of the ObjectId represent the time in seconds since the UNIX epoch. The next 3 bytes of the ObjectId represent the machine identifier. The next 2 bytes of the ObjectId represent the process ID.

Should I use MongoDB ObjectId?

You should NOT convert the ObjectId in the database to a string, and then compare it to another string. If you'd do this, MongoDB cannot use the _id index and it'll have to scan all the documents, resulting in poor query performance. Show activity on this post. Don't.


1 Answers

You can use following regular expression but it will not quite work

checkForHexRegExp = /^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i 

Example:

> checkForHexRegExp.test("112345679065574883030833") false > checkForHexRegExp.test("FFFFFFFFFFFFFFFFFFFFFFFF") false > checkForHexRegExp.test("45cbc4a0e4123f6920000002") true 

But, as I commented, 112345679065574883030833, FFFFFFFFFFFFFFFFFFFFFFFF are also valid hexadecimal representations.

You should use /^[a-f\d]{24}$/i because it passes all the above tests

like image 90
falsetru Avatar answered Sep 19 '22 14:09

falsetru