0

I am looking at updating array objects in mongodb documents as below

var cursor = db.coll.find();
cursor.forEach(function(x){
  if(x.arr) {
    x.arr.forEach(function(y,i){
      if(y.field1) {
        db.coll.update({_id: x._id}, {$set:{'arr.'+i+'.field1': 'x' + y.field1}})
      }
    })
  }
})

I get a syntax error at {$set:{'arr.'+i+'.field1': 'x' + y.field1}} Is there a workaround?

1 Answer 1

1

You are trying to dynamically assign values to the key of JavaScript object at the initialization time. Just create it separately and assign the key at a later step.

var cursor = db.coll.find();
cursor.forEach(function(x){
  if(x.arr) {
    x.arr.forEach(function(y,i){
      if(y.field1) {
        var setStmt = {};
        setStmt['arr.'+i+'.field1'] = 'x' + y.field1;
        db.coll.update({_id: x._id}, {$set: setStmt});
      }
    })
  }
})
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.