1

I am using Micronaut framework with JAVA and trying to validate the objectId with the below string.

60236833af6a1d49478d2bef   // Valid mongo ObjectId

60236833a46a1d49478d2bef  // Invalid mongo ObjectId

How can I perform either the string has valid objectId or not in Java with MongoDb?

prasad_
  • 12,755
  • 2
  • 24
  • 36
San Jaisy
  • 15,327
  • 34
  • 171
  • 290
  • Please note the above two strings are valid hexadecimal string representations. Both are valid strings and can be used to construct a `ObjectId`. – prasad_ Feb 10 '21 at 09:12

2 Answers2

2

This work for me

import org.bson.types.ObjectId;

if(ObjectId.isValid(value)){
}
San Jaisy
  • 15,327
  • 34
  • 171
  • 290
0

You can refer to the ObjectId specification for how they are generated.

Any 24-character hexadecimal string should be convertable to an ObjectId.

D. SM
  • 13,584
  • 3
  • 12
  • 21