How to update values using pymongo?

后端 未结 4 874
挽巷
挽巷 2020-12-04 15:19

I\'ve a mongodb collection in this form:

{id=ObjectId(....),key={dictionary of values}}
where dictionary of values is {\'a\':\'1\',\'b\':\'2\'.....}
<         


        
相关标签:
4条回答
  • 2020-12-04 15:46

    Something I did recently, hope it helps. I have a list of dictionaries and wanted to add a value to some existing documents.

    for item in my_list:
        my_collection.update({"_id" : item[key] }, {"$set" : {"New_col_name" :item[value]}})
    
    0 讨论(0)
  • 2020-12-04 15:49

    You can use the $set syntax if you want to set the value of a document to an arbitrary value. This will either update the value if the attribute already exists on the document or create it if it doesn't. If you need to set a single value in a dictionary like you describe, you can use the dot notation to access child values.

    If p is the object retrieved:

    existing = p['d']['a']
    

    For pymongo versions < 3.0

    db.ProductData.update({
      '_id': p['_id']
    },{
      '$set': {
        'd.a': existing + 1
      }
    }, upsert=False, multi=False)
    

    For pymongo versions >= 3.0

    db.ProductData.update_one({
      '_id': p['_id']
    },{
      '$set': {
        'd.a': existing + 1
      }
    }, upsert=False)
    

    However if you just need to increment the value, this approach could introduce issues when multiple requests could be running concurrently. Instead you should use the $inc syntax:

    For pymongo versions < 3.0:

    db.ProductData.update({
      '_id': p['_id']
    },{
      '$inc': {
        'd.a': 1
      }
    }, upsert=False, multi=False)
    

    For pymongo versions >= 3.0:

    db.ProductData.update_one({
      '_id': p['_id']
    },{
      '$inc': {
        'd.a': 1
      }
    }, upsert=False)
    

    This ensures your increments will always happen.

    0 讨论(0)
  • 2020-12-04 15:55

    in python the operators should be in quotes: db.ProductData.update({'fromAddress':'http://localhost:7000/'}, {"$set": {'fromAddress': 'http://localhost:5000/'}},{"multi": True})

    0 讨论(0)
  • 2020-12-04 15:59

    With my pymongo version: 3.2.2 I had do the following

    from bson.objectid import ObjectId
    import pymongo
    
    client = pymongo.MongoClient("localhost", 27017)
    db = client.mydbname
    
    db.ProductData.update_one({
      '_id': ObjectId(p['_id']['$oid'])
    },{
      '$set': {
        'd.a': existing + 1
      }
    }, upsert=False)
    
    0 讨论(0)
提交回复
热议问题