簡體   English   中英

pymongo中無法更新現有文檔中的字段

[英]Can't update field in existing document in pymongo

我正在嘗試使用pymongo將字段添加到現有文檔中。

這是我的代碼:

from pymongo import MongoClient

client = MongoClient()
db = client['profiles']
collection = db['collection']


def createFields():
    collection.update({'_id' : '547f21f450c19fca35de53cd'}, {'$set': {'new_field':1}})

createFields()

當我在mongoDB解釋器中輸入以下內容時

>use profiles
>db.collection.find()

我可以看到沒有任何字段添加到指定的文檔。

_id字段最常見的類型是ObjectId(),它是十二個字節的值,而不是您在此處提供的24字節的字符串。

您必須使用正確的類型才能匹配文檔。

您應該在腳本之前添加db

嘗試一下,對我來說很好

在Mongo CLI中

> use profiles
> db.collection.insertOne({'_id': '547f21f450c19fca35de53cd'})
> db.collection.find()
{ "_id" : "547f21f450c19fca35de53cd" }

Python腳本-> test.py

from pymongo import MongoClient
client = MongoClient()
db = client['profiles']
collection = db['collection']

def createFields():
    db.collection.update({'_id' : '547f21f450c19fca35de53cd'}, {'$set': {'new_field':-881}})

createFields()

命令行

> python test.py

Mongo CLI

> use profiles
> db.collection.find()
> { "_id" : "547f21f450c19fca35de53cd", "new_field" : -881 }

對於pymongo,請使用update_oneupdate_many而不是update

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM