Question

I want to add a value to an array that is inside another array. My document is like:

{categories:[{categoryName:"a category", items:[{itemName:"an item", arrayOfValues:[1]}]}]}

I would like to use $addToSet to arrayValues. To do so I am doing an update with a query

table.update({"categories.items.itemName" : "anItem"}, {$addToSet: "categories.$.items.$.arrayOfValues":"10"})

but I get an error: can't append to array using string field name [$]

What am I doing wrong? Is it possible to update with nested arrays?

Thanks

Was it helpful?

Solution

Arrays inside arrays is considered bad mongodb design right now (mainly because you can't manipulate them efficiently, using $addToSet and friends). And you took it one step further and created arrays inside arrays inside arrays!

I understand that schema-less nature of MongoDB can cause a feeling that you can throw documents of any structure into it and handle them later. Unfortunately, this is not the reality. You have to know what you're doing, what features and limitations are there. In this case, you can't use positional operator to push element to a nested array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top