并发 - 以线程安全的方式获取通过Java插入的对象的MongoDB生成的ID [英] Concurrency - Getting the MongoDB generated ID of an object inserted via Java in a thread safe way

查看:244
本文介绍了并发 - 以线程安全的方式获取通过Java插入的对象的MongoDB生成的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取通过Java插入的文档的Mongo生成的ID的最佳方法是什么。

What is the best method to get the Mongo generated ID of a document inserted via Java.

插入文档的Java进程是多线程的,这意味着我们需要一些原子方法来插入和返回对象的ID。

The Java process inserting the documents is multi-thread, meaning that we need some atomic way to insert and return the ID of the object.

此外,如果我们设置一个唯一索引,如果对象是重复的,将返回ID?

Also, if we setup a unique index, in the event that the object is a duplicate, will an ID be returned?

谢谢!

推荐答案

早期生成ObjectId,在插入中使用它,并且不需要让数据库将它返回给你。
ObjectId不使用共享的序列号是唯一的,所以如果在生成一个序列之前插入或检索它是没有关系的。

Generate the ObjectId early, use it in the insert, and there will no need to have the database return it to you. ObjectId doesn't use a shared sequence number to be unique, so it doesn't matter if you generate one before inserting or retrieve it after.

public ObjectId createThing() {
    ObjectId result = new ObjectId();
    BasicDBObject thingToInsert = new BasicDbObject();
    thingToInsert.put('_id', result);
    //set other fields here
    collection.insert(thingToInsert);
    return result;
}

这篇关于并发 - 以线程安全的方式获取通过Java插入的对象的MongoDB生成的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆