How to stop insertion of Duplicate documents in a mongodb collection

后端 未结 4 1845
孤城傲影
孤城傲影 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:11

    You should use a compound index on the set of fields that uniquely identify a document within your MongoDB collection. For example, if you decide that the combination of user, title and Bank are your unique key you would issue the following command:

    db.collection.createIndex( { user: 1, title: 1, Bank: 1 }, {unique:true} )
    

    Please note that this should be done after you have removed previously stored duplicates.

    http://docs.mongodb.org/manual/tutorial/create-a-compound-index/

    http://docs.mongodb.org/manual/tutorial/create-a-unique-index/

提交回复
热议问题