pymongo 中的等效方法:
import pymongo
from bson.json_util import dumps
db = pymongo.MongoClient()['mydatabase']
# Data setup
db.collection.insert_many([{'state': 'was_lowercase'}, {'randomrecord': 'without state field'}])
# search all matching records
records = db.collection.find({"state": {"$exists": True}})
# loop through and update each record
for doc in records:
db.collection.update_one({'_id': doc['_id']},
{"$set": {"state": doc['state'].upper()}})
# pretty up the results
print(dumps(db.collection.find({}, {'_id': 0}), indent=4))
如果使用 pymongo >= 3.9.0 和 mongodb >= 4.2,update_many 可以采用管道运算符:
import pymongo
from bson.json_util import dumps
db = pymongo.MongoClient()['mydatabase']
# Data setup
db.collection.insert_many([{'state': 'was_lowercase'}, {'randomrecord': 'without state field'}])
# update using pipeline
db.collection.update_many({"state": {"$exists": True}},
[{'$set': {'state': {'$toUpper': '$state'}}}])
# pretty up the results
print(dumps(db.collection.find({}, {'_id': 0}), indent=4))
无论哪种方式都会给出结果:
[
{
"state": "WAS_LOWERCASE"
},
{
"randomrecord": "without state field"
}
]