[英]MongoDB change field type in array
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: 虽然我已经能够在已解决的stackoverflow问题中将“ date_add”字段从String更改为ISODate:
How to change the field type of "product_quantity" to Integer? 如何将“ product_quantity”的字段类型更改为Integer?
I've tried the following in the mongo shell: 我在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. 然后,我尝试使用PyMongo,尽管能够提取文档并使用字典方法和for循环来遍历列表并更改值,但我不知道如何将文档更新回数据库。
A Solution in the mongo shell or python would be of tremendous help. mongo shell或python中的解决方案将有很大帮助。
Thank you for your time and effort! 感谢您的时间和精力!
Use replace_one, with the document's _id as the criterion: 使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.