Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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]}}})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading