Exploring
Exploring

Reputation: 3359

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

Upvotes: 2

Views: 16488

Answers (6)

Usama Shoaib
Usama Shoaib

Reputation: 27

String str_id = JSONObj.getId().asObjectId().getValue().toString());

Upvotes: 0

Raman Mishra
Raman Mishra

Reputation: 1

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

Upvotes: 0

krishna chandak
krishna chandak

Reputation: 401

import org.bson.types.ObjectId;

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

String id = idObj.toString()

Upvotes: 0

Manish
Manish

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

Omar Perez
Omar Perez

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

Exploring
Exploring

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

Related Questions