Mass update of all objects in an array

253 views
Skip to first unread message

Ian L.

unread,
Aug 27, 2010, 1:11:47 AM8/27/10
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?

Eliot Horowitz

unread,
Aug 27, 2010, 9:52:10 AM8/27/10
to mongod...@googlegroups.com
There isn't a way to do what you want right now using an operator.

Do you really need to though?  If you're just setting to 0, your code could treat null and 0 the same?


--
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com.
To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.


Ian L.

unread,
Aug 27, 2010, 11:53:19 AM8/27/10
to mongodb-user
On Aug 27, 6:52 am, Eliot Horowitz <eliothorow...@gmail.com> wrote:
> There isn't a way to do what you want right now using an operator.
>
> Do you really need to though?  If you're just setting to 0, your code could
> treat null and 0 the same?

I guess so.

The background is that MongoKit, which lets you declare a schema for
your documents, has a bug in verion 0.5 where it requires all keys of
nested objects in arrays even if they're omitted from the required-
fields list. I was hoping for an easy way to "migrate" all of my
documents when I added something to the schema. (The author says v0.6
will fix this.)

Thanks :)
Reply all
Reply to author
Forward
0 new messages