在创建过程中返回空白对象的ID

时间:2012-10-09 09:18:15

标签: java mongodb

我想创建一个对象,获取它的'_id',将其更改为String并将其作为参数传递给另一个对象。

思想是这样的,但它不起作用

BasicDBObject doc = new BasicDBObject();
a.insert(doc);
String id = doc.getString("$oid");

1 个答案:

答案 0 :(得分:0)

你可以这样做:

ObjectId myId = new ObjectId(); //id is created here
DBObject myObject = new BasicDBObject();
myObject.put("_id", myId);

// Whether you save myObject to Mongo or not at this moment, you have its id
String myIdString = myId.toString();
// Now you can save myObject's id string in another object, and then later on,
// If you want to recreate the myId object you can do so:
ObjectId myIdRecreated = new ObjectId(myIdString);

换句话说,实例化ObjectId并将其传递给DBObject的“_id”字段意味着ObjectId将是该DBObject的id。通过这种方式,您无需将DBObject显式保存到Mongo以获取其ID。