add/push 嵌套数组中的数据如何 Mongodb
How add/push data in nested array in Mongodb
这是我在 mongoAltas 中的 collection:
{
"_id":{"$oid":"5ff35fefa0652d23c637bf51"},
"plantId":"3",
"status":"SUCCESS",
"healthMonitor":[{"PlantName":""}]
}
当我尝试将任何数据插入嵌套数组“PlantName”时,文档未更新且 returns 为空。我尝试了 $push
和 $set
并尝试了 find_one_and_update
和 update_one
但两者都不起作用
这是我试过的更新:
collection.find_one_and_update({'plantId':3},
{ '$push': {
"healthMonitor.$.PlantName": "Herb"
}
})
collection.find_one_and_update({'plantId':3},
{ '$push': {
"healthMonitor":[{PlantName": "Herb"}]
}
})
如果有人知道嵌套文档的代码如何工作,请帮助我。
PlantName
不是“嵌套数组”。 healthMonitor
是一个包含单个项目的数组,它是一个包含一个字段的对象:PlantName
.
您的更新无效,因为您的数据是字符串 "3"
,但您的更新过滤器是数字 3
。
如果要更新数组第一个元素中的 PlantName
字段,请使用:
collection.update_one({'plantId': '3'}, {'$set': {'healthMonitor.0.PlantName': 'Herb'}})
此外,要在现有文档记录的对象数组中插入新数据对象,可以使用以下代码:
collection.update_one({'plantId':'3'}, {'$push': {'healthMonitor':
{'PlantName': 'tomato'}}})
这是我在 mongoAltas 中的 collection:
{
"_id":{"$oid":"5ff35fefa0652d23c637bf51"},
"plantId":"3",
"status":"SUCCESS",
"healthMonitor":[{"PlantName":""}]
}
当我尝试将任何数据插入嵌套数组“PlantName”时,文档未更新且 returns 为空。我尝试了 $push
和 $set
并尝试了 find_one_and_update
和 update_one
但两者都不起作用
这是我试过的更新:
collection.find_one_and_update({'plantId':3},
{ '$push': {
"healthMonitor.$.PlantName": "Herb"
}
})
collection.find_one_and_update({'plantId':3},
{ '$push': {
"healthMonitor":[{PlantName": "Herb"}]
}
})
如果有人知道嵌套文档的代码如何工作,请帮助我。
PlantName
不是“嵌套数组”。 healthMonitor
是一个包含单个项目的数组,它是一个包含一个字段的对象:PlantName
.
您的更新无效,因为您的数据是字符串 "3"
,但您的更新过滤器是数字 3
。
如果要更新数组第一个元素中的 PlantName
字段,请使用:
collection.update_one({'plantId': '3'}, {'$set': {'healthMonitor.0.PlantName': 'Herb'}})
此外,要在现有文档记录的对象数组中插入新数据对象,可以使用以下代码:
collection.update_one({'plantId':'3'}, {'$push': {'healthMonitor':
{'PlantName': 'tomato'}}})