问题
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