1

I have a mongodb collection like this:-

{
    "_id": ObjectId("52174bcb834806830e5447"),
    "roles": [
        {
            "role": "admin"
        },
        {
            "role": "user"
        }
    ]
}

I need to add a new 'role' to the roles array. Like this {"role": "guest" }. How do I do that?

2 Answers 2

4

You can do this with the $push-operator

This should work:

 db.collection.update(
     { _id:  ObjectId("52174bcb834806830e5447") },
     { $push: { roles: { role: "guest" } } }
 );
Sign up to request clarification or add additional context in comments.

Comments

1

In addition, you may use $addToSet to avoid duplicates.

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.