Reputation: 35
I have a MongoDB collection that has a notes section that contains nested associative arrays (see schema below). I am having issues inserting a new note. Ideally I would like to do something like this
var label_var = '3';
db.collection.update({ _id: ObjectID(id) }, { $set: { notes.label_var : data} } ...
Unfortunately dot notation does not take variables and I can't use notes[label_var] in an update statement. Any help is appreciated.
Schema:
[
{
_id: GUID,
title: 'title',
notes: {
'1': {
content: 'content here'
},
'2': {
content: 'content here'
}
}
}
]
Upvotes: 1
Views: 1433
Reputation: 311835
Build your $set
value programmatically prior to your update
call:
var label_var = '3';
var set_value = {};
set_value['notes.' + label_var] = data;
db.collection.update({ _id: ObjectID(id) }, {$set: set_value}, ...);
Upvotes: 1