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.

asked Jun 10, 2010 at 19:47

1 Answer 1

6

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.

answered Jun 10, 2010 at 21:52
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.