pymongo如何大写文档字段?

时间:2019-12-18 12:00:19

标签: pymongo pymongo-3.x

我想用update_many(findQuery,updateQuery)用pymongo将文档的一个字段从小写更新为大写。我有相同的mongo查询,但我想通过pymongo做到这一点。有什么办法可以实现?

db.collection.find({ "state": { "$exists": true } }).forEach(function(doc) {
  db.collection.update(
    { "_id": doc._id },
    { "$set": { "state": doc.state.toUpper() } }
    );   
});

1 个答案:

答案 0 :(得分:0)

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"
    }
]