Pymongo ドキュメントのチュートリアルに従っています
import pymongo
from pymongo import MongoClient
import datetime
client = MongoClient("mongodb://localhost:27017/")
test_db = client.test_db #This creates a database
posts = test_db.posts #This creates a collection of documents
post = {"author": "Doug",
"text": "My first blog post!",
"tags": ["mongodb", "python"],
"date": datetime.datetime.utcnow()}
post_id = posts.insert_one(post).inserted_id
コードはどちらの場合でも機能します。IDE で実行を押すか、Python コンソールで 1 行ずつ実行します。ただし、Python コンソールで実行すると、
が表示されます。
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: text_database.another_collection index: _id_ dup key: { _id: ObjectId('5f505d1e233d210283dd4632') }, full error: {'index': 0, 'code': 11000, 'keyPattern': {'_id': 1}, 'keyValue': {'_id': ObjectId('5f505d1e233d210283dd4632')}, 'errmsg': "E11000 duplicate key error collection: text_database.another_collection index: _id_ dup key: { _id: ObjectId('5f505d1e233d210283dd4632') }"}
エラー。新しい空のコレクションを作成してドキュメントを挿入する場合、重複エラーを除いて正常です。理由を聞いてもいいですか?
------------------------
insert_one() の後、ポスト辞書は次のようになります。
>>>print(post)
{'_id': ObjectId('5f506285b54093f4b9202abe'),
'author': 'Doug',
'date': datetime.datetime(2020, 9, 3, 3, 27, 1, 729287),
'tags': ['mongodb', 'python'],
'text': 'My first blog post!'}
同じ投稿を再度挿入しようとすると、_id フィールドがあるため、エラーがスローされます。
その後辞書を更新したくない場合は、サート。辞書のコピーを使用して挿入できます。 dict(post) または post.copy() を使用して辞書のコピーを作成できます。
これで、以下のようにインサートを変更できるようになります。
post_id = posts.insert_one(dict(post)).inserted_id
または
post_id = posts.insert_one(post.copy()).inserted_id
2
ご返信いただきありがとうございます。投稿を再度挿入しませんでした。実際、insert_one はエラーを引き起こしませんが、insert_id は重複エラーを引き起こします。
– アンデス ラム
2020 年 9 月 3 日 3:46
inserted_id は挿入が成功した後の結果であるため、エラーは発生しません。 insert_one() は成功すると InsertOneResult を返します
– デッドショット
2020 年 9 月 3 日 3:48