3

I want to use '$set' to update an embedded document, but the field is a variable.

Say I have a document like:

{'_id': ObjectID,
 'people': {
     'A': {'age': 20}
 }
}

Now I want to add a new person to people. I can use $set: {'people.B':{'age': 25}, but what if the name(instead B) is a variable?

I am using Node.js 5.1 and 'mongodb' driver.

1
  • It sounds like people should be an array. Is there a reason why you are explicitly labeling the objects 'A', 'B', etc.? Commented Nov 30, 2015 at 14:16

1 Answer 1

1

You need to build your query dynamically using the [] operator.

var b = 'B';
var update = {};
update['people.' + b] = { 'age': 25 };
db.collection.update({}, { '$set': update })
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.