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

后端 未结 2 1665
没有蜡笔的小新
没有蜡笔的小新 2021-01-19 19:13

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

相关标签:
2条回答
  • 2021-01-19 19:35

    Try this @ebt_dev:

    db.collection("collectionname").insertOne(data, { forceServerObjectId: false })
    
    0 讨论(0)
  • 2021-01-19 19:43

    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.

    0 讨论(0)
提交回复
热议问题