先說下需求(我把需求簡化了下),看下圖。現在有很多人選了自己要上的課程,數據存mongo里,但是發現courses中id=2的【數學】,名稱錄入錯誤了,或者說id=2的數學課程,名稱需要更新成“高等數學”。
一開始按照老套路直接去update,會報一個錯。Write failed with error code 16837 and error message 'cannot use the part (......) to traverse the element......
然后網上找了很多方法去嘗試,發現spring的mongoTemplate文檔很多比較亂,也不詳細。
最終還是給折騰出來了。
-
// 用到的package
-
import org.springframework.data.mongodb.core.MongoTemplate;
-
import org.springframework.data.mongodb.core.query.Criteria;
-
import org.springframework.data.mongodb.core.query.Query;
-
import org.springframework.data.mongodb.core.query.Update;
-
-
// 主要代碼
-
Update update = Update.update(
"courses.$.name",
"高等數學").set(
"courses.$.code",
"GDSX");
-
Query query =
new Query(Criteria.where(
"sex").is(
"男").and(
"courses.id").is(
2));
-
WriteResult wr = mongoTemplate.updateMulti(query, update, Student.class);
-
System.out.println(
"受影響的行數================>" + wr.getN());
最終打印結果是受影響行數為2。更新了2條數據。更新完的數據如下圖: