I am really facing challenge in changing String object to ObjectId using BSON API. The error I am facing:
Exception in thread "main" java.lang.IllegalArgumentException: invalid ObjectId [7887978]
at org.bson.types.ObjectId.<init>(ObjectId.java:130)
at org.bson.types.ObjectId.<init>(ObjectId.java:124)
at com.sample.common.Main.main(Main.java:8)
The simple code below for reference:
import org.bson.types.ObjectId;
public class Main {
public static void main(String[] args) {
String number = "7887978";
ObjectId id = new ObjectId(number);
System.out.println(id);
}
}
How we can solve this error. Any pointers ?
Edit: Maven dependency that I used:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>2.3</version>
</dependency>
Point here is the
string
has to be a valid24-byte
hexadecimal
value. The value7887978
is invalid. You could either modify the code as below:or use the in build static API
get()
to create a new object id..Hope it helps you!
docs say :
so perhaps
"7887978"
is not a valid id