mongodb - How to update the Embedded Data which is inside of another Embedded Data? -
i have document below in mongodb:
{ "_id": "test", "tasks": [ { "name": "task1", "parameter": [ { "name": "para1", "type": "string", "value": "*****" }, { "name": "para2", "type": "string", "value": "*****" } ] }, { "name": "task2", "parameter": [ { "name": "para1", "type": "string", "value": "*****" }, { "name": "para2", "type": "string", "value": "*****" } ] } ] }
there embedded data structure (parameter) inside of embedded data structure (tasks). want update para1 in task1's parameter.
i have tried many ways can use query tasks.parameter.name find para1 cannot update it. example in doc using .$.
update value in embedded data structure doesn't work in case.
anyone have ideas ?
mongodb supports positional operator once, , top level array. there ticket server-831 change behavior use case. can follow issue there , vote it.
however, might able change approach accomplish want do. 1 way change schema. collapse tasks name array document looks this:
{ _id:test, tasks: [ { task:1 name:para1, type:string, value:***** }, { task:1 name:para2, type:string, value:***** }, { task:2 name:para1, type:string, value:***** }, { task:2 name:para2, type:string, value:***** } ] }
another approach may work use $pull , $push. instance replace task (this assumes tasks.parameter.name unique array of parameters):
db.test2.update({$and: [{"tasks.name": "task3"}, {"tasks.parameter.name":"para1"}]}, {$pull: {"tasks.$.parameter": {"name": "para1"}}}) db.test2.update({"tasks.name": "task3"}, {$push: {"tasks.$.parameter": {"name": "para3", type: "string", value: 1}}})
with solution need careful regard concurrency, there brief moment document doesn't exist.
Comments
Post a Comment