mongodb: should i always use the 'safe' option on updates

后端 未结 3 1764
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-08 10:58

when dealing with mongodb, when should i use the {safe: true} on queries?

Right now I use the \'safe\' option just to check if my queries were inserted or updated succes

3条回答
  •  清酒与你
    2021-02-08 11:52

    Here is another use case where unsafe writes are an appropriate choice: You are making a large number of writes in very short order. In this case you might perform a number of writes, and then call get last error to see if any of them failed.

    collection.setWriteConcern(WriteConcern.NORMAL)
    collection.getDB().resetError()
    List<
    for (Something data : importData) {
        collection.insert(makeDBObject(data))
    }
    collection.getDB().getLastError(WriteConcern.REPLICAS_SAFE).throwOnError()
    

    If this block succeeds without an exception, then all of the data was inserted successfully. If there was an exception, then one or more of the write operations failed, and you will need to retry them (or check for a unique index violation, etc). In real life, you might call getLastError every 10 writes or so, to avoid having to resubmit lots of requests.

    This pattern is very nice for performance when performing bulk inserts of large amounts of data.

提交回复
热议问题