Adding new element to array in MongoDb

无人久伴 提交于 2019-12-11 04:48:12

问题


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?


回答1:


You can do this with the $push-operator

This should work:

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



回答2:


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



来源:https://stackoverflow.com/questions/18438362/adding-new-element-to-array-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!