我想创建一个对象,获取它的“_id”,将其更改为字符串并将其作为参数传递给另一个对象。
想法是这样的,但它不起作用
BasicDBObject doc = new BasicDBObject();
a.insert(doc);
String id = doc.getString("$oid");
你可以这样做:
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。