MongoDB:插入具有特定ID的文档,而不是自动生成的ObjectID [英] MongoDB: insert documents with specific id instead of auto generated ObjectID
问题描述
我需要使用Java在MongoDB上插入文档(使用特定ID代替自动生成的ObjectID).
I need to insert documents on MongoDB (with specific id instead of auto generated ObjectID) using java..
-
要插入一个文档或更新(如果存在),我尝试使用
findOne
搜索ID,如果不存在,请先insert
id,然后再findAndModify
.它可以工作,但是我不认为这是有效的方法,很费时间.有没有更好的方法可以做到这一点?
To insert one document or update if exist, I tried use
findOne
to search for the id, if it doesn't exist theninsert
the id and thenfindAndModify
. 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?
任何帮助将不胜感激
推荐答案
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.
这篇关于MongoDB:插入具有特定ID的文档,而不是自动生成的ObjectID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!