Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

How add/push data in nested array in Mongodb

This is my collection in mongoAltas:


{
    "_id":{"$oid":"5ff35fefa0652d23c637bf51"},
    "plantId":"3",
    "status":"SUCCESS",
    "healthMonitor":[{"PlantName":""}]
}

When I am trying to insert any data to the nested array "PlantName", the document is not updated and returns null. I tried $push and $set and tried find_one_and_update and just update_one but both does not work

Here is the update I tried:

collection.find_one_and_update({'plantId':3}, 
                        {  '$push': {
                            "healthMonitor.$.PlantName": "Herb"
                                }
                        })

collection.find_one_and_update({'plantId':3}, 
                        {  '$push': {
                            "healthMonitor":[{PlantName": "Herb"}]
                                }
                        })

If any one know how the code works for nested document please help me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

PlantName is not a "nested array". healthMonitor is an array that contains a single item, which is an object containing one field: PlantName.

Your update is not working as your data is string "3" but your update filter is on numeric 3.

If you want to update the PlantName field in the first element of the array, use:

collection.update_one({'plantId': '3'}, {'$set': {'healthMonitor.0.PlantName': 'Herb'}})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...