I'm trying to add a new message (with key "3") to the nested "messages" document but $addToSet or $push won't work. Is it possible to push a new message element to such a structure? In the beginning the messages property was an array but my mongodb provider converts arrays into such structures. Just for your information: I'm accessing the mongodb via node.js and mongojs but a native mongodb solution would be perfect too.
{
"messages" :
{
"0" :
{
"foo": "bar0"
},
"1" :
{
"foo": "bar1"
},
"2" :
{
"foo": "bar2"
},
},
"name" : "MyName"
}
The problem is that the editor of MongoSoup automatically transforms arrays into a collection of documents. When I create the array via command line or my node.js application then everything is like I've expected it.
Thank you anyway ... my bad!
Essentially you just want to add a subdocument, so simply $setting the document will work:
db.bar.update({_id : ObjectId("542194f8b32cda36885e1d9e") }, {$set : {"messages.3" : {"foo" : "bar3"}}})
You would need to substitute an appropriate match criteria rather than the _id I used of course based on what your real documents look like. Full procedure for adding/updating your sample document as follows:
> foo = {
"messages" : {
"0" : {
"foo" : "bar0"
},
"1" : {
"foo" : "bar1"
},
"2" : {
"foo" : "bar2"
}
},
"name" : "MyName"
}
> db.bar.insert(foo)
WriteResult({ "nInserted" : 1 })
> db.bar.findOne()
{
"_id" : ObjectId("542194f8b32cda36885e1d9e"),
"messages" : {
"0" : {
"foo" : "bar0"
},
"1" : {
"foo" : "bar1"
},
"2" : {
"foo" : "bar2"
}
},
"name" : "MyName"
}
> db.bar.update({_id : ObjectId("542194f8b32cda36885e1d9e") }, {$set : {"messages.3" : {"foo" : "bar3"}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.bar.findOne()
{
"_id" : ObjectId("542194f8b32cda36885e1d9e"),
"messages" : {
"0" : {
"foo" : "bar0"
},
"1" : {
"foo" : "bar1"
},
"2" : {
"foo" : "bar2"
},
"3" : {
"foo" : "bar3"
}
},
"name" : "MyName"
}
The obvious limitation is that this would overwrite any existing messages.3 field if it already exists, so you will need to be careful and you need to keep track of the latest message in the field also.