Ian L.
unread,Aug 27, 2010, 1:11:47 AM8/27/10Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to mongodb-user
I'm using MongoDB 1.6.1.
Documents in one of my databases look somewhat like this:
{ items: [ { foo: 1 }, { foo: 2 }, { foo: 3 } ] }
{ items: [ { foo: 4 }, { foo: 5 }, { foo: 6 } ] }
I decided that I wanted to add a new attribute, bar, to all of the
nested objects with a default value, 0, like so:
{ items: [ { foo: 1, bar: 0 }, { foo: 2, bar: 0 }, { foo: 3, bar:
0 } ] }
...
My first attempt was this:
> db.tests.update( {}, { $set: { 'items.$.bar': 0 } }, false, true )
can't append to array using string field name [$]
Later it dawned on me that the dollar is a placeholder for the matched
index, so I needed to match some indexes. I then tried:
> db.tests.update( { 'items.$.foo': { $exists:1 } }, { $set:
{ 'items.$.bar': 0 } }, false, true )
Which resulted in only updating the first object without foo in items:
{ items: [ { foo: 1, bar: 0 }, { foo: 2 }, { foo: 3 } ] }
{ items: [ { foo: 4, bar: 0 }, { foo: 5 }, { foo: 6 } ] }
Further runs of the above update will add a bar to the second object
in items, and so on.
I must be missing something. How can I add an attribute to *every*
object in a list?