简体   繁体   中英

MongoDB: insert documents with specific id instead of auto generated ObjectID

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

  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?

  2. 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?

Any help will be appreciated

For your first problem MongoDB has upsert so

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

or in the Java driver

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

If you want to set a custom ID you just set the _id key manually ie

yourBasicDBObject.put("_id",yourCustomId) 

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

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

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

试试这个@ebt_dev:

db.collection("collectionname").insertOne(data, { forceServerObjectId: false })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM