MongoDB:不能在同一文档中插入两次 [英] MongoDB : Can't insert twice the same document

查看:58
本文介绍了MongoDB:不能在同一文档中插入两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的pymongo代码上,两次插入相同的文档会引发错误:

On my pymongo code, inserting twice the same doc raises an error :

document = {"auteur" : "romain",
            "text" : "premier post",
            "tag" : "test2",
            "date" : datetime.datetime.utcnow()}
collection.insert_one(document)
collection.insert_one(document)

提高:

DuplicateKeyError: E11000 duplicate key error collection: test.myCollection index: _id_ dup key: { : ObjectId('5aa282eff1dba231beada9e3') }

插入两个内容不同的文档会很好.

inserting two documents with different content works fine.

似乎类似于 https://docs. mongodb.com/manual/reference/method/db.collection.createIndex/#options 我应该做一些关于索引的选项:

Seems like according to https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#options I should do something aobut option of indexes:

unique  boolean 
Optional. Creates a unique index so that the collection will not accept insertion or update of documents where the index key value matches an existing value in the index.

Specify true to create a unique index. The default value is false.

The option is unavailable for hashed indexes.

推荐答案

添加到Peba的答案中,您可以使用python字典的.copy()方法来避免文档本身的变异.

Adding to Peba's answer, you can use the .copy() method of python dictionary to avoid the mutation of the document itself.

document = {"auteur" : "romain",
            "text" : "premier post",
            "tag" : "test2",
            "date" : datetime.datetime.utcnow()}
collection.insert_one(document.copy())
collection.insert_one(document.copy())

这样,每个insert_one调用都会得到document的浅表副本,同时使您的代码更具pythonic性.

This way, each insert_one call get's a shallow copy of the document and at the same time keeps your code more pythonic.

这篇关于MongoDB:不能在同一文档中插入两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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