如何停止在 mongodb 集合中插入重复文档 [英] How to stop insertion of Duplicate documents in a mongodb collection

查看:17
本文介绍了如何停止在 mongodb 集合中插入重复文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们有一个 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 更新.Update 将查找与您的查询匹配的文档,然后它会修改您想要的字段,然后您可以告诉它 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆