mongo中原始数据
{
"_id": {
"$numberLong": "7085200805669904384"
},
"message": "Thank you for your support",
"announcement": "weekend",
"created_user_id": {
"$numberLong": "8637022162191"
},
"update_time": {
"$date": "2022-12-15T06:24:00.193Z"
},
"status": "1",
"subscribers": [
{
"boolean": false,
"userId": {
"$numberLong": "8637022162191"
}
}
]
}
给subscribers 字段新增一条数据
public static void main(String[] args) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(7085200805669904384L));
Update update = new Update();
Map<String, Object> sub = new HashMap<>();
sub.put("userId", 8637022162191L);
sub.put("boolean", false);
update.push("subscribers", sub);
mongoTemplate.updateFirst(query, update, "store_time_away");
}
给subscribers 字段删除一条数据
public static void main(String[] args) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(7085200805669904384L));
Update update = new Update();
Map<String, Object> sub = new HashMap<>();
sub.put("userId", 8637022162191L);
update.pull("subscribers", sub);
mongoTemplate.updateFirst(query, update, "store_time_away");
}
给subscribers 编辑一条数据
public static void main(String[] args) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(7085200805669904384L))
.addCriteria(Criteria.where("subscribers.userId").is(8637022162191L));
Update update = new Update();
//不预先查询文档我们就不知道要修改数组的元素的下标。这时定位操作符“$”
update.set("subscribers.$.boolean",false);
mongoTemplate.updateFirst(query, update, "store_time_away");
}
查询
public static void main(String[] args) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(7085200805669904384L))
.addCriteria(Criteria.where("subscribers.userId").is(8637022162191L));
StoreTimeAwayV1 storeTimeAways = mongoTemplate.findOne(query, StoreTimeAwayV1.class);
}