MongoDB:插入具有特定ID的文档,而不是自动生成的ObjectID

MongoDB:插入具有特定ID的文档,而不是自动生成的ObjectID

问题描述:

我需要使用Java在MongoDB上插入文档(使用特定ID代替自动生成的ObjectID).

I need to insert documents on MongoDB (with specific id instead of auto generated ObjectID) using java..

  1. 要插入一个文档或更新(如果存在),我尝试使用findOne搜索ID,如果不存在,请先insert id,然后再findAndModify.它可以工作,但是我不认为这是有效的方法,很费时间.有没有更好的方法可以做到这一点?

  1. To insert one document or update if exist, I tried use findOne to search for the id, if it doesn't exist then insert the id and then findAndModify. It works but I don't feel that it's efficient way, it's time consuming. Is there a better way to achieve that?

要一次插入多个文档,我正在关注

To insert multiple documents at once,I'm following this solution. but I don't know how I can insert my custom Id instead of objectID?

任何帮助将不胜感激

对于您的第一个问题,MongoDB具有

For your first problem MongoDB has upsert so

db.collection.update(
   {query for id},
   {document},
   {upsert: true}
)

Java驱动程序

yourCollection.update(searchObject, modifiedObject, true, false);

如果要设置自定义ID,只需手动设置_id键,即

If you want to set a custom ID you just set the _id key manually i.e.

yourBasicDBObject.put("_id",yourCustomId) 

您只需要确保每个文档的唯一性即可.

you just have to ensure it is unique for each document.

您还需要在modifiedObject中设置_id,否则将生成新的.

You will also need to set the _id in your modifiedObject otherwise a new one will be generated.

对于批量操作,只需通过提供_id键为每个文档设置自定义ID也将起作用.

As for the bulk operations, just setting a custom ID for each document by giving the _id key should also work.