0

I know that this is working:

db.users.update({_id: "1234"}, {$set: {"conversations.partId": id}});

In result I've got: conversations:{"partId":2345}

but I would like to set partId as a variable. And to have structure like this: conversations:{"3456":"2345"}

I have tried:

db.users.update({_id: "someid"}, {$set: {"conversations".partId: id}});
or
db.users.update({_id: "someid"}, {$set: {"conversations"+partId: id}});

But this is of course not working

Can anyone help me?

1 Answer 1

1

Try creating the document you need to update via the bracket notation, i.e.

var obj = {};
obj[partId] = id;

You can then use that as a new embedded document to add to the conversations field with the $set operator expression as follows:

db.users.update(
    {_id: "someid"}, 
    {
        $set: {
            "conversations": obj
        }
    }
);
Sign up to request clarification or add additional context in comments.

2 Comments

thank you this is working. But is there a better way of adding another key:value than fetching from database existing key:value's, adding them to that obj and $set'ing conversation object from start? I'm thinking about something like $addToSet or $push but for objects
If you are updating the existing schema to have the key:value relationship then the only way is updating the embedded documents using a loop and if you are using MongoDB versions > 2.6 then bulk operations can improve the performance. Other than that I don't see any other better way, and for the record, $addToSet or $push operators work on arrays.

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.