MongoDB: embed documents with a specific identifier instead of an automatically generated ObjectID

I need to insert documents in MongoDB (with a specific identifier instead of the automatically generated ObjectID) using java ..

  • To insert a single document or update if it exists, I tried to use findOneto search for an identifier, if it does not exist, then an insertidentifier, and then findAndModify. It works, but I don’t feel that this is an effective way, it takes a lot of time. Is there a better way to achieve this?

  • To insert multiple documents at once, I follow this decision . but i don't know how can i insert my own id instead of objectID?

Any help would be appreciated

+4
source share
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 user identifier, just set the key _idmanually, i.e.

yourBasicDBObject.put("_id",yourCustomId) 

you just have to make sure that it is unique to each document.

You also need to install _idin yours modifiedObject, otherwise a new one will be generated.

As for bulk operations , only setting a user identifier for each document with a key should also work _id.

+6
source

Try this @ebt_dev:

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

All Articles