[英]How do I insert another nested document using pymongo?
Ahoy,哎呀,
I have a document that looks like this:我有一个看起来像这样的文档:
{"_id": "123abc456def",
"name": "John Smith",
"address": [
{"street": "First St.", "date": "yesterday", "last_updated": "two days ago"}
],
"age": 123}
I try to add another street document using $push, it errors out with:我尝试使用 $push 添加另一个街道文件,它会出错:
pymongo.errors.WriteError: The field 'address' must be an array but is of type object in document {_id: ObjectId('6049e88657e43d8801197c72')}
pymongo.errors.WriteError:字段“地址”必须是一个数组,但在文档 {_id: ObjectId('6049e88657e43d8801197c72')} 中的类型为 object
Code I'm using:我正在使用的代码:
mydb3 = myclient["catalogue"]
mycolALL = mydb3["locations"]
query = {"charID": 0}
newvalue = {"$push": {"address": {"street": "test123", "date": "test123", "last_updated": "now123"}}}
mycolALL.update_one(query, newvalue)
Not making an address book or anything, just edited it so it makes a bit more sense to anyone without context.没有制作地址簿或任何东西,只是对其进行了编辑,这样对于没有上下文的任何人来说都更有意义。
My desired output would be that the document would look like this:我想要的 output 将是该文档将如下所示:
{"_id": "123abc456def",
"name": "John Smith",
"address": [
{"street": "First St.", "date": "yesterday", "last_updated": "two days ago"},
{"street": "test123", "date": "test123", "last_updated": "now123"}
],
"age": 123}
Normally I can google my way to an answer that makes the coin drop and JACKPOT.通常我可以用谷歌搜索答案,使硬币掉落和累积奖金。 but this time I'm outta luck.
但这次我运气不好。
$set = it just changes the existing document, effectively replacing it. $set = 它只是更改现有文档,有效地替换它。 Which is not what I want.
这不是我想要的。
$addToSet = for arrays only, error message: "pymongo.errors.WriteError: Cannot apply $addToSet to non-array field. Field named 'address' has non-array type object" $addToSet = 仅适用于 arrays,错误消息:“pymongo.errors.WriteError:无法将 $addToSet 应用于非数组字段。名为“地址”的字段具有非数组类型对象”
Anyone that can help?有谁能帮忙吗?
Just a guess but are you sure you're looking at the right data / database.只是一个猜测,但您确定您正在查看正确的数据/数据库。
Based on the data you posted your update_one()
won't update that record because it doesn't match your filter {"charID": 0}
根据您发布的数据,您的
update_one()
不会更新该记录,因为它与您的过滤器不匹配{"charID": 0}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.