如何停止在mongodb集合中插入重复的文档 [英] How to stop insertion of Duplicate documents in a mongodb collection
问题描述
让我们有一个 MongoDB
集合,它有三个文档。
Let us have a MongoDB
collection which has three docs..
db.collection.find
db.collection.find()
{ _id:'...', user: 'A', title: 'Physics', Bank: 'Bank_A' }
{ _id:'...', user: 'A', title: 'Chemistry', Bank: 'Bank_B' }
{ _id:'...', user: 'B', title: 'Chemistry', Bank: 'Bank_A' }
我们有一个文档,
doc = { user: 'B', title: 'Chemistry', Bank:'Bank_A' }
如果我们使用
db.collection.insert(doc)
这里,这个重复的文档将被插入数据库。
here, this duplicate doc will get inserted in database.
{ _id:'...', user: 'A', title: 'Physics', Bank: 'Bank_A' }
{ _id:'...', user: 'A', title: 'Chemistry', Bank: 'Bank_B' }
{ _id:'...', user: 'B', title: 'Chemistry', Bank: 'Bank_A' }
{ _id:'...', user: 'B', title: 'Chemistry', Bank: 'Bank_A' }
如何停止此重复项。在哪个字段应该建立索引或者其他方法?
How this duplicate can be stopped. On which field should indexing be done or any other approach?
推荐答案
使用使用 upsert = true
更新。更新将查找与您的查询匹配的文档,然后它将修改您想要的字段,然后您可以告诉它upsert:如果您想要插入,如果没有文档匹配您的查询,则为True。
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(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
所以,例如,你可以使用这样的:
So, for your example, you could use something like this:
db.collection.update(doc, doc, {upsert:true})
这篇关于如何停止在mongodb集合中插入重复的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!