'mongodb how to convert _id to String in JAVA

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");


Solution 1:[1]

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.

Solution 2:[2]

With MongoDb Driver version 3 and using Document object.

        Document temp = hwCursor.next();
        temp.getObjectId("_id").toString();

or

temp.getObjectId("_id").toHexString();

Solution 3:[3]

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!

Solution 4:[4]

import org.bson.types.ObjectId;

ObjectId idObj = (ObjectId)obj.get("_id");

String id = idObj.toString()

Solution 5:[5]

BsonObjectId bid = (BsonObjectId) result.get("_id");
String str = bId.getValue.toString();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Exploring
Solution 2 Manish
Solution 3 Omar Perez
Solution 4 Community
Solution 5 Syscall