【问题标题】:MongoDB change field type in arrayMongoDB更改数组中的字段类型
【发布时间】:2016-12-09 16:34:56
【问题描述】:

我的文档结构如下:

> 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",
                        }
                ]
        },
 }

虽然我能够在 stackoverflow 上已经回答的问题的帮助下将“date_add”字段从 String 更改为 ISODate,但我仍然坚持:

如何将“product_quantity”的字段类型改为Integer?

我在 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); 
});

然后我尝试使用 PyMongo,虽然我能够提取文档并使用字典方法和 for 循环来迭代列表并更改值,但我不知道如何将文档更新回数据库。

mongo shell 或 python 中的解决方案会有很大帮助。

感谢您的时间和精力!

【问题讨论】:

  • 你是对的。尽管我的主要问题是如何找到列表中的元素,但应该进行更彻底的搜索。

标签: python mongodb pymongo


【解决方案1】:

使用replace_one,以文档的_id为标准:

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)

【讨论】:

    猜你喜欢
    • 2020-11-14
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    相关资源
    最近更新 更多