0

I've documents with the following structure:

> db.orders.find().limit(1).pretty()
{
        "_id" : ObjectId("5846bf0e141be215b814f64a"),
        "date_add" : ISODate("2016-10-10T11:55:24Z"),
        "associations" : {
                "order_rows" : [
                        {
                                "product_id" : "31",
                                "product_quantity" : "1",
                        },
                        {
                                "product_id" : "133",
                                "product_quantity" : "1",
                        }
                ]
        },
 }

while I was able to change the "date_add" field from String to ISODate with the help of the already answered questions on stackoverflow I'm stuck with:

How to change the field type of "product_quantity" to Integer?

I've tried the following in the mongo shell:

db.orders.find().forEach(function(x){
x.associations.order_rows.product_quantity = new NumberInt(x.associations.order_rows.product_quantity);
db.orders.save(x); 
});

I then tried to use PyMongo and while I was able to extract the document and use the dictionary methods and a for loop to iterate over the list and change the value, I've no idea how to update the document back in the database.

A Solution in the mongo shell or python would be of tremendous help.

Thank you for your time and effort!

2
  • Possible duplicate of Update field type in mongo Commented Dec 9, 2016 at 17:00
  • you're right. should've searched more thoroughly although my main problem was how to get to the element in the list. Commented Dec 12, 2016 at 8:47

1 Answer 1

1

Use replace_one, with the document's _id as the criterion:

from pymongo import MongoClient

collection = MongoClient().test.c

# Sort to avoid seeing a doc multiple times if the update causes it to move.
for doc in collection.find().sort('_id'):
    rows = doc.get('associations', {}).get('order_rows', [])
    for row in rows:
        if 'product_quantity' in row:
            row['product_quantity'] = int(row['product_quantity'])

    collection.replace_one({'_id': doc['_id']}, doc)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.