数据准备:
db.getCollection("hello100").insertOne({
"name":"zhangsan",
"edu":[
{
"time":"2000",
"school":"yizhong"
},
{
"time":"2003",
"school":"qinghua"
}
]
});
更新第一个元素:添加属性:attr = abc
db.getCollection("hello100").updateOne(
{
"name":"zhangsan"
}, {
"$set":{
"edu.0.attr":"abc"
}
});
更新第二个元素:添加属性:attr = def
db.getCollection("hello100").updateOne(
{
"name":"zhangsan"
}, {
"$set":{
"edu.1.attr":"def"
}
});
查询结果:
db.getCollection("hello100").find();
{
"_id": ObjectId("6698c1c519290000490014d4"),
"name": "zhangsan",
"edu": [
{
"time": "2000",
"school": "yizhong",
"attr": "abc"
},
{
"time": "2003",
"school": "qinghua",
"attr": "def"
}
]
}