Let's say you need to add a field to every document in a collection.
import pymongo
client = pymongo.MongoClient('localhost', 27017)
db = client.mydb.mycollection
for doc in db.find():
db.update(
{'_id': doc['_id']},
{'$set': {'newField': 10} }, upsert=False, multi=False)
The find
method returns a Cursor
, on which you can easily iterate over using the for in
syntax.
Then, we call the update
method, specifying the _id
and that we add a field ($set
). The parameters
upsert
and multi
come from mongodb (see here for more info).