Question
Let us have a MongoDB collection which has three docs..
db.collection.find()
We have a doc,
If we use
- db.collection.insert(doc)
How this duplicate can be stopped. On which field should indexing be done or any other approach?
How-To
Don't use insert.
Use update with upsert=true. Update will look for the document that matches your query, then it will modify the fields you want and then, you can tell it upsert:True if you want to insert if no document matches your query.
- db.collection.update(
-
, -
, - {
- upsert: <boolean>,
- multi: <boolean>,
- writeConcern:
- }
- )
- db.collection.update(doc, doc, {upsert:true})
* [ MongoDB 文件 ] Getting Started - Update Data with Java Driver
沒有留言:
張貼留言