tags:

views:

45

answers:

1

I'm trying to come up with a way to update the values in an array of objects in mongo. I have a collection which looks like

   [
     { CourseName: '',
       Sessions: [
              {
                 _id: null, //oops I didn't set this in the import
                 Name: 'blah',
                 Location: 'moon'
              }]
     }
    ]

Now I need to set the _id field. I tried the documented approach of doing

db.Course.update({'Sessions._id': null}, {$set:{'Sessions.$._id': ObjectId()}}, false, true)

But I ran into this bug http://jira.mongodb.org/browse/SERVER-1055 which meant that I couldn't do it. Is there some syntax which will allow me just to itterate over the collection and update each record by hand? I tried a few things like

db.Course.find().forEach(
    function(course) 
    {
        course.Sessions.forEach(function(session)
            {
                session._id=ObjectId();
                course.Save(session); //Don't know how to save a single object
            });
    });

but they didn't work. I'm looking for some way to just update that value in each session.

+2  A: 

I think what you want is:

db.Course.find().forEach(
    function(course) 
    {
        course.Sessions.forEach(function(session)
            {
                session._id=ObjectId();
            });
        db.Course.save(course);
    });

However, you can run into problems saving stuff into a collection you're in the middle of iterating over, so I'd suggest loading a bunch of documents into an array, processing them, loading another batch, etc.

kristina
Beautiful, thanks.
stimms