Home > Mobile >  Delete the last four characters in the same field in all documents in mongodb with Python
Delete the last four characters in the same field in all documents in mongodb with Python

Time:10-29

I have the following document structure in mongodb in one collection:

Company = {
    name : Google
    sector : tech
    id_number: 12345XYZ5
    ...
}

I need to delete the last four characters of the field id_number (XYZ5) so that this field matches the field of another collection, that I will have to do a lookup. In the other collection, Google has the id_number 1234.

How can I do that with Python?

My guess is that it works over update_many, but I don't know how I can delete the last four characters in the specific field in all the documents of a collection.

CodePudding user response:

You can use the $substr operator to get the first 4 characters of the id_number field and then use the $set operator to update the id_number field with the new value.

db.collection.update_many({}, {'$set': {'id_number': {'$substr': ['$id_number', 0, 4]}}})
  • Related