接口IMongDaoUpdate:
package com.net.test.mongdb.dao; import com.net.test.mongdb.entity.User; public interface IMongDaoUpdate { public void updateUser(User user); public void updateUserHobby(User user); public void updateUserHobbyDiffer(User user); public void updateUserUserPsg(User user); public void deleteUserUserPsg(String name,String field); }
实现类:
package com.net.test.mongdb.dao.imp; import javax.annotation.Resource; 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; import org.springframework.stereotype.Repository; import com.net.test.mongdb.dao.IMongDaoUpdate; import com.net.test.mongdb.entity.User; /** * @author *** * @Time:2017年8月4日 下午1:50:16 * @version 1.0 * Function: TODO */ @Repository public class MongDaoUpdateImp implements IMongDaoUpdate { @Resource protected MongoTemplate mongoTemplate; /** * @description 单条更新user信息 * @param user */ @Override public void updateUser(User user) { Query query = Query.query(Criteria.where("name").is(user.getName())); Update up = new Update(); up.set("sex", user.getSex()).inc("age", user.getAge()).set("hobby", user.getHobby()); mongoTemplate.updateFirst(query, up, User.class); } /** * @description 单独对user信息的某个特定数组字段继续追加数据,不管是否重复 * @param user */ @Override public void updateUserHobby(User user) { Query query = Query.query(Criteria.where("name").is(user.getName())); Update up = new Update(); String[] str = new String[user.getHobby().size()]; for(int i = 0 ; i < user.getHobby().size();i++) { str[i] = user.getHobby().get(i).toString(); } up.pushAll("hobby", str); mongoTemplate.updateFirst(query, up, User.class); } /** * @description 一次性追加多个不重复的数组元素 * @param user */ @Override public void updateUserHobbyDiffer(User user) { Query query = Query.query(Criteria.where("name").is(user.getName())); Update up = new Update(); Object[] str = new Object[user.getHobby().size()]; for(int i = 0 ; i < user.getHobby().size();i++) { str[i] = user.getHobby().get(i).toString(); } up.addToSet("hobby").each(str); mongoTemplate.updateFirst(query, up, User.class); } /** * @description 更新内置对象 * @param user */ @Override public void updateUserUserPsg(User user) { Query query = Query.query(Criteria.where("name").is(user.getName())); Update update = new Update(); update.set("psg.address", user.getPsg().getAddress()); update.set("psg.phone", user.getPsg().getPhone()); update.set("psg.county", "江苏"); mongoTemplate.updateFirst(query, update, User.class); } /** * @description 删除内置对象的某个字段 * @param name * @param field */ @Override public void deleteUserUserPsg(String name, String field) { Query query = Query.query(Criteria.where("name").is(name)); Update update = new Update(); update.unset("psg.county"); mongoTemplate.updateFirst(query, update, User.class); } }