Mongodb avoid duplicate entries

后端 未结 6 706
情歌与酒
情歌与酒 2020-12-08 14:34

I am newbie to mongodb. May I know how to avoid duplicate entries. In relational tables, we use primary key to avoid it. May I know how to specify it in Mongodb using java?<

6条回答
  •  甜味超标
    2020-12-08 15:11

    I am not a Java programmer however you can probably convert this over.

    MongoDB by default does have a primary key known as the _id you can use upsert() or save() on this key to prevent the document from being written twice like so:

    var doc = {'name': 'sam'};
    db.users.insert(doc); // doc will get an _id assigned to it
    db.users.insert(doc); // Will fail since it already exists
    

    This will stop immediately duplicates. As to multithread safe inserts under certain conditions: well, we would need to know more about your condition in that case.

    I should add however that the _id index is unqiue by default.

提交回复
热议问题