1

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'
            }
        }
    }
]

1 Answer 1

1

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}, ...);
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.