Adam Van Oijen
Adam Van Oijen

Reputation: 545

Can't update field in existing document in pymongo

I'm trying to add a field in to an existing document with pymongo.

here is my code:

from pymongo import MongoClient

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


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

createFields()

when I enter the following in to the mongoDB interpreter

>use profiles
>db.collection.find()

I can see that there have not been any fields added to the specified document.

Upvotes: 0

Views: 826

Answers (2)

Tony Chou
Tony Chou

Reputation: 604

You should add db before your script

Just try this, it works fine for me

In Mongo CLI

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

Python Script -> 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()

Command Line

> python test.py

Mongo CLI

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

For pymongo, use update_one or update_many instead of update

Upvotes: 0

Asya Kamsky
Asya Kamsky

Reputation: 42352

An _id field is most commonly of type ObjectId() which is a twelve byte value, rather than a 24-byte string as you are providing here.

You must use the correct type in order to match the document.

Upvotes: 1

Related Questions