$set operator interpreting array index as object index in mongodb -
mongodb seems interpret $set
paths numerical components object keys rather array indexes if field has not been created array.
> db.test.insert({_id: "one"}); > db.test.update({_id: "one"}, {$set: {"array.0.value": "cheese"}}); > db.find({_id: "one"}) { "_id": "one", "array": { "0" : { "value" : "cheese" } }
i expected "array": [{"value": "cheese"}]
, instead initialized object key string "0".
i array initializing whole array, so:
> db.test.update({_id: "one"}, {$set: {"array": [{"value": "cheese"}]}});
... clobber existing properties , other array elements might have been set.
is there way convince $set
want "array" array type, following constraints:
- i want execute in single query, without looking record first.
- i want preserve existing array entries , object values
in short, want behavior of $set: {"array.0.value": ... }
if "array" had been initialized array, without knowing whether or not has. possible?
i not sure if possible without lookup. perhaps can change schema design, , try this:
db.test.insert({_id: "one"}); db.test.update({_id: "one"}, {$addtoset: {array: { $each:['cheese', 'ham'] }}}); db.test.findone({_id:'one'}); // { "_id" : "one", "array" : [ "cheese", "ham" ] }
handling array elements (sub-documents in array) in mongodb pain. https://jira.mongodb.org/browse/server-1243
Comments
Post a Comment