How to stop insertion of Duplicate documents in a mongodb collection

后端 未结 4 1839
孤城傲影
孤城傲影 2020-11-30 01:26

Let us have a MongoDB collection which has three docs..

db.collection.find()

 { _id:\'...\', user: \'A\', title: \'Physics\',   Bank: \'         


        
4条回答
  •  再見小時候
    2020-11-30 02:08

    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: ,
         multi: ,
        writeConcern: 
       }
      )
    

    So, for your example, you could use something like this:

    db.collection.update(doc, doc, {upsert:true})
    

提交回复
热议问题