Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

mongodb

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

like image 591
ebt_dev Avatar asked Oct 09 '14 08:10

ebt_dev


2 Answers

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 i.e.

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.

like image 120
Trudbert Avatar answered Oct 14 '22 05:10

Trudbert


Try this @ebt_dev:

db.collection("collectionname").insertOne(data, { forceServerObjectId: false })
like image 29
bhaRATh Avatar answered Oct 14 '22 05:10

bhaRATh