在带有 Java 驱动程序的 mongoDB 中获取最后插入文档的 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3338999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get ID of last inserted document in a mongoDB w/ Java driver
提问by Matt W
Is there an easy way to get the ID (ObjectID) of the last inserted document of a mongoDB instance using the Java driver?
是否有一种简单的方法可以使用 Java 驱动程序获取 mongoDB 实例的最后插入文档的 ID (ObjectID)?
采纳答案by Matt W
I just realized you can do this:
我刚刚意识到你可以这样做:
BasicDBObject doc = new BasicDBObject( "name", "Matt" );
collection.insert( doc );
ObjectId id = (ObjectId)doc.get( "_id" );
回答by chx
I do not know about the Java driver but for posterity, the getLastError command can be run to get the _id of a write, even an upsert (as of 1.5.4)
我不知道 Java 驱动程序,但为了后代,可以运行 getLastError 命令来获取写入的 _id,甚至是 upsert(从 1.5.4 开始)
回答by Ramesh
After a document is inserted into the MongoDB collection, the successful insertion should update required fields (viz. _id). You may query the inserted object for the _id.
将文档插入 MongoDB 集合后,成功插入应更新必填字段(即 _id)。您可以查询插入的对象的 _id。
回答by zlob
It's safe to do
这样做是安全的
doc.set("_id", new ObjectId())
if you look at driver code
如果您查看驱动程序代码
if ( ensureID && id == null ){
id = ObjectId.get();
jo.put( "_id" , id );
}
public static ObjectId get(){
return new ObjectId();
}
回答by user27
This is insert operation:
这是插入操作:
DBCollection table1 = db.getCollection("Collection name");
BasicDBObject document = new BasicDBObject();
document.put("_id",value);
document.put("Name", name);
table1.insert(document);
After insert u get last inserted id:
插入后你得到最后插入的id:
DBCollection tableDetails = db.getCollection("collection name");
BasicDBObject queryDetails = new BasicDBObject();
queryDetails.put("_id", value);
DBCursor cursorDetails =tableDetails.find(queryDetails);
DBObject oneDetails;
oneDetails=cursorDetails.next();
String data=oneDetails.get("_id").toString();
System.out.println(data);
after getting value convert to inter type.
获取值后转换为内部类型。
回答by Jadiel de Armas
To avoid casting from Object
to ObjectId
, given a com.mongodb.client.MongoCollection collection
and a org.bson.Document doc
, you can do the following:
为了避免从Object
to 转换ObjectId
,给定 acom.mongodb.client.MongoCollection collection
和 a org.bson.Document doc
,您可以执行以下操作:
collection.insert(doc);
ObjectId id = doc.getObjectId("_id");
回答by Z.Billy
In MongoTemplate.class has a method
在 MongoTemplate.class 中有一个方法
protected <T> void doInsert(String collectionName, T objectToSave, MongoWriter<T> writer) {
assertUpdateableIdIfNotSet(objectToSave);
initializeVersionProperty(objectToSave);
maybeEmitEvent(new BeforeConvertEvent<T>(objectToSave, collectionName));
DBObject dbDoc = toDbObject(objectToSave, writer);
maybeEmitEvent(new BeforeSaveEvent<T>(objectToSave, dbDoc, collectionName));
Object id = insertDBObject(collectionName, dbDoc, objectToSave.getClass());
populateIdIfNecessary(objectToSave, id);
maybeEmitEvent(new AfterSaveEvent<T>(objectToSave, dbDoc, collectionName));
}
and the method will set id for us
该方法将为我们设置 id
protected void populateIdIfNecessary(Object savedObject, Object id) {
if (id == null) {
return;
}
if (savedObject instanceof BasicDBObject) {
DBObject dbObject = (DBObject) savedObject;
dbObject.put(ID_FIELD, id);
return;
}
MongoPersistentProperty idProp = getIdPropertyFor(savedObject.getClass());
if (idProp == null) {
return;
}
ConversionService conversionService = mongoConverter.getConversionService();
MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(savedObject.getClass());
PersistentPropertyAccessor accessor = entity.getPropertyAccessor(savedObject);
if (accessor.getProperty(idProp) != null) {
return;
}
new ConvertingPropertyAccessor(accessor, conversionService).setProperty(idProp, id);
}
we can see if the entity is a sub-class of BasicDBObject,it will set a id for us.
我们可以看到实体是否是 BasicDBObject 的子类,它会为我们设置一个 id。
回答by Matthew
I think the answer to this is "No".
我认为这个问题的答案是“不”。
What you can do is provide your the _id
yourself, either manually, or implement the CollectibleCodec
mechanism (which is exactly what BasicBDDocument
does). However all these solutions involve generating the ID clientside.
您可以做的是_id
手动提供您自己,或实现该CollectibleCodec
机制(正是这样BasicBDDocument
做的)。然而,所有这些解决方案都涉及生成 ID 客户端。
Having said that, I don't think there's any problem with generating the _id
clientside.
话虽如此,我认为生成_id
客户端没有任何问题。