Skip to content
Advertisement

pymongo update all documents in collection for field with it’s substring value

{'some': 'abcdefg', 'some2': 'hijklmn'}

Desired output

{'some': 'abc', 'some2': 'hij'}

in other words substring [:3]

How can I achieve this with pymongo

Advertisement

Answer

You can use updatemany with an aggregation : https://docs.mongodb.com/manual/tutorial/update-documents-with-aggregation-pipeline/

update_pipe =   [
                      { "$set":
                              { "some":
                                      { "$substr":  ['$some', 0,3]}
                              },
                      },
                       
                      { "$set":
                              { "some2":
                                      { "$substr":  ['$some2', 0,3]}
                              },
                      }
                  ]
collection.update_many({}, update_pipe)
Advertisement