【问题标题】:how to upper case document field with pymongo?如何用pymongo大写文档字段?
【发布时间】:2020-04-10 23:32:43
【问题描述】:

我想使用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() } }
    );   
});

【问题讨论】:

    标签: pymongo pymongo-3.x


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 2023-01-23
      • 1970-01-01
      • 2013-01-04
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2020-08-09
      相关资源
      最近更新 更多