Sparky
Sparky

Reputation: 4879

Adding new element to array in MongoDb

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?

Upvotes: 1

Views: 135

Answers (2)

danidelvalle
danidelvalle

Reputation: 146

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

Upvotes: 1

Philipp
Philipp

Reputation: 69663

You can do this with the $push-operator

This should work:

 db.collection.update(
     { _id:  ObjectId("52174bcb834806830e5447") },
     { $push: { roles: { role: "guest" } } }
 );

Upvotes: 4

Related Questions