0

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

Matroska
  • 6,885
  • 14
  • 63
  • 99

1 Answers1

3

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.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • @RemonvanVliet: did you not notice this link in my answer? :) – Sergio Tulentsev Feb 15 '12 at 11:18
  • @SergioTulentsev, I notice that you said "manipulate them efficiently". I encountered [this answer about `$push`](http://stackoverflow.com/questions/27874469/mongodb-push-in-nested-array), which also seems to work for `$addToSet`. Is it just not efficient? Do you have any thoughts about how inefficient it is? – Mike Spear Jul 21 '16 at 03:24