I tried converting my String ID to MongoDB ObjectID
public class relevancy_test extends Object implements Comparable<ObjectId> {
public static void main(String[] args) throws UnknownHostException {
MongoClient mongo = new MongoClient("localhost", 27017);
DB mydb = mongo.getDB("test");
DBCollection mycoll = mydb.getCollection("mytempcoll");
BasicDBObject query = null;
Map<ObjectId, DBObject> updateMap = new HashMap<ObjectId, DBObject>();
List<DBObject> dbobj = null;
DBCursor cursor = mycoll.find();
dbobj = cursor.toArray();
for (DBObject postObj : dbobj) {
String id = postObj.get("_id").toString();
ObjectId objId = new ObjectId((String) postObj.get("_id"));
updateMap.put(objId, postObj);
}
}
}
Here (String) postObj.get("_id")
is of form "8001_469437317594492928_1400737805000"
On running following error shows up
Exception in thread "main" java.lang.IllegalArgumentException: invalid ObjectId [8001_469437317594492928_1400737805000]
at org.bson.types.ObjectId.<init>(ObjectId.java:181)
at org.bson.types.ObjectId.<init>(ObjectId.java:167)
at fetch_data_tanmay.relevancy_test.main(relevancy_test.java:48)
I am able to convert String to ObjectId like below:
Here I am updating zip code of 'address' collection, suppose you will get REST api input like below:
Now I have to find address record based on the above mentioned id (which is an ObjectId in mongodb). I have a mongorepository for that, and using below code to find the the Address record:
And use this repository method in your service class, like:
While retrieving from List cast it directly to ObjectId
ObjectId is a 12-byte BSON type
Here your string "8001_469437317594492928_1400737805000" is not 12 byte BSON type. so update according to ObjectId
To generate a new ObjectId using the ObjectId() constructor with a unique hexadecimal string:
Please make string correct to convert string to objectId.
As I see there are two issue here:
The value
8001_469437317594492928_1400737805000
is not a HEX value which you can see in the DB but an explicit concatenation of time, machine id, pid and counter components. This components are used to generate HEX value. To get HEX value you need to use method ToString of your ObjectID instance.Reference to explanation of ObjectID components here: http://api.mongodb.com/java/current/org/bson/types/ObjectId.html
In order to create new ObjectID instance with specific HEX value use this:
var objectId = new ObjectId(hexStringId)
Here is an example that will serve you: