I have the following schema:
{
"name" : "MyName",
"actions" : [{
"kind" : "kind1",
"result" : "result1"
},
{
"kind":"kind1",
"result":"result1"
}
]
}
I want to insert a new field called 'expected' in different subdocument in actions. I tried the following command but I have an issue with it:
db.tasks.update({},{$push:{ "actions.expected" : "MyExpected" }},false,true)
can't append to array using string field name expected
You can use the $addToSet functionality:
http://docs.mongodb.org/manual/reference/operator/update/addToSet/
Try
db.tasks.update({}, {$addToSet: {'actions.expected': 'MyExpected'}})
You have json object inside array but in the query you are trying to add string. Thats why you got an exception. You can update your query as follows.
db.tasks.update({},{$push:{ "actions" : {"expected" : "MyExpected"} }},false,true)
Well, the problem is that you're trying to $push
into an array, but the destination you're giving is not an array.
actions.expected
is the expected
field in the actions
field, and you're pushing "MyExpected"
into that array - but such an array does not exist.
Let's assume you had the following data, perhaps that explains it best. Your query would work on a data structure like this:
actions : { expected : [] } // actions is an object here
// ... {$push:{ "actions.expected" : "MyExpected" }}
actions : { expected : ["MyExpected"] }
Instead, you'll probably want to push an object into the actions array:
actions : []
$push : { "actions" : { "expected" : "MyExpected" } }
actions : [ { "expected" : "MyExpected" } ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.