我!!!永遠!!!爲!!!爆棧!!!打call!!!
當初使用mongo時,沒用過多考慮更新的問題,採取了雙層嵌套格式來存儲數據,現在需求變動,要有更新,百度了一天,沒有解決,爆哭,嘗試在爆棧搜索解決方法,又又又又一次,爆棧救了我的命!!!
我的文檔格式
{
"_id" : "1",
"personCerts" : [
{
"perId" : "546",
"perName" : "老壇酸菜",
"certifications" : [
{
"certId" : "111",
"regType" : "aaa",
"type" : "二級"
}
]
},
{
"perId" : "334",
"perName" : "朱浩",
"certifications" : [
{
"certId" : "01438668",
"regType" : "wwww",
"type" : "二級"
},
{
"certId" : "222",
"regType" : "ttt",
"type" : "二級"
}
]
},
{
"perId" : "788",
"perName" : "牛大龍",
"certifications" : [
{
"certId" : "01365043",
"regType" : "rrr",
"type" : "二級"
}
]
},
{
"perId" : "677",
"perName" : "高恆",
"certifications" : [
{
"certId" : "滬231191921594",
"regType" : "RY_ZCLB_072",
"type" : "二級"
}
]
},
{
"perId" : "45667",
"perName" : "袁慧",
"certifications" : [
{
"certId" : "00640150",
"regType" : "uuu",
"type" : "二級"
}
]
}
],
"createDate" : ISODate("2020-05-17T09:21:25.790Z"),
"lastUpdate" : ISODate("2020-06-23T05:59:45.624Z")
},{
"_id" : "2",
"personCerts" : [
{
"perId" : "1",
"perName" : "kk",
"certifications" : [
{
"certId" : "5443",
"regType" : "aaa",
"type" : "二級"
}
]
}
],
"createDate" : ISODate("2020-05-17T09:21:25.790Z"),
"lastUpdate" : ISODate("2020-06-23T05:59:45.624Z")
}
更新需求爲 :將 _id = 1 ,perId = 334 , certId = 222 的 regType 更新爲 ooo
爆棧的寫法:
模仿後,我的寫法
Bson filters = Filters.and(Filters.eq("_id","1"),
Filters.elemMatch(
"personCerts",
Filters.and(
Filters.eq("perId","334"),
Filters.elemMatch("certifications",Filters.eq("certId","222"))
)
)
);
Bson update = Updates.set("personCerts.$.certifications.$[certification].regType","OOO");
Bson filter = Filters.eq("certification.certId", "222");
UpdateOptions updateOptions = new UpdateOptions().arrayFilters(Collections.singletonList(filter));
MongoCollection<Document> collection = mongoTemplate.getDb().getCollection("col");
documents.updateOne(filters,update,updateOptions);