Reputation: 3359
I am reading mongo collection from java code. When I am trying to read the _id
value, I am getting the following:
{"$oid":"541333629520f6e05b0cb410"}
I am reading like: jsonObject.get("_id")
from java code. I was expecting something like: "_id" : "541333629520f6e05b0cb410"
Here I am looking for a way so that I can get the _id as a string in one operation.
So far I have been trying the following:
JSONObject idObj = (JSONObject)JSONObj.get("_id");
ObjectId objectId = (ObjectId) idObj.get("$oid");
Upvotes: 2
Views: 16488
Reputation: 27
String str_id = JSONObj.getId().asObjectId().getValue().toString())
;
Upvotes: 0
Reputation: 1
BsonObjectId bid = (BsonObjectId) result.get("_id");
String str = bId.getValue.toString();
Upvotes: 0
Reputation: 401
import org.bson.types.ObjectId;
ObjectId idObj = (ObjectId)obj.get("_id");
String id = idObj.toString()
Upvotes: 0
Reputation: 1775
With MongoDb Driver version 3 and using Document object.
Document temp = hwCursor.next();
temp.getObjectId("_id").toString();
or
temp.getObjectId("_id").toHexString();
Upvotes: 2
Reputation: 23
This worked for me:
String objectId = (String) result.get("_id.$oid");
Maybe there's better ways to do it. Let me know if it works for you.
Cheers!
Upvotes: 2
Reputation: 3359
Workaround this issue using the following snippet:
JSONObject idObj = (JSONObject)obj.get("_id");
String strID = (String) idObj.get("$oid");
May be there are some other way to do this in a better way.
Upvotes: 2