1

Suppose I have collection with following data.

{
     _id: ObjectID(....),
     ...
     data : [ 23, 34]
}

I have following JavaScript function.

function reduce(array){
    //some computation
    return result; // not array
}

Is there any way to update all the collection using MongoDB shell with following net effect.

{
    data : reduce(data)
}

Edit:

I am looking to execute this for only one time as part of migration.

2
  • You can make use of stored functions: docs.mongodb.org/manual/tutorial/… Commented Apr 3, 2015 at 8:26
  • I am looking to execute this for only one time as part of migration. Commented Apr 3, 2015 at 9:57

1 Answer 1

1

Sure, you could iterate over MongoDB cursor using cursor.forEach() method and saving processed documents with db.collection.save() method, e.g.:

db.collection.find().forEach(function(doc) {
  doc.data = reduce(doc.data); // update field
  db.collection.save(doc); // save
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.