参考:https://docs.mongodb.com/manual/reference/method/db.collection.update/#update-parameter
1. MongoDB删除数组元素
如下文档:
contact: {
phone: [
{
number: "+1786543589455",
place: "New Jersey",
createdAt: ""
}
{
number: "+1986543589455",
place: "Houston",
createdAt: ""
}
]
}
要删除number为+1786543589455的子文档,则命令为:
collection.update(
{ _id: id },
{ $pull: { 'contact.phone': { number: '+1786543589455' } } }
);
根据索引位或值删除元素:
{
"_id" : ObjectId("4d1cb5de451600000000497a"),
"name" : "dannie",
"interests" : [
"guitar",
"programming",
"gadgets",
"reading"
]
}
删除interests中的第3个元素:
db.lists.update({_id:id}, {$unset : {"interests.2" : 1 }})
删除interests中的gadgets值:
db.lists.update({_id:id}, {$pull:{"interests":"gadgets"}})
2. 修改元素内的某一项
db.collection.update({"_id" : "2a9eab52901347afb7a0837e123c65a8"},{"onlineStatus" : true},{ upsert: true })