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!

Sven Tenscher
  • 185
  • 1
  • 15
  • Possible duplicate of [Update field type in mongo](http://stackoverflow.com/questions/36429475/update-field-type-in-mongo) – styvane Dec 09 '16 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. – Sven Tenscher Dec 12 '16 at 08:47

1 Answers1

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)
A. Jesse Jiryu Davis
  • 23,641
  • 4
  • 57
  • 70