接口IMongDaoDelete:
package com.net.test.mongdb.dao; public interface IMongDaoDelete { public void deleteByName(String name); public void deleteLikeName(String name); public void deleteArrFirst(String name); public void pullDomArray(String name,String key,String value); }
实现类:
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.data.mongodb.core.query.Update.Position; import org.springframework.stereotype.Repository; import com.net.test.mongdb.dao.IMongDaoDelete; import com.net.test.mongdb.entity.User; /** * @author **** * @Time:2017年8月4日 上午10:34:06 * @version 1.0 * Function: Delete */ @Repository public class MongDaoDeleteImp implements IMongDaoDelete{ @Resource protected MongoTemplate mongoTemplate; /** * @description 单条精确删除对象 * @param name */ @Override public void deleteByName(String name) { Query query = Query.query(Criteria.where("name").is(name)); mongoTemplate.remove(query, User.class); } /** * @description 模糊删除对象,批量 * @param name */ @Override public void deleteLikeName(String name) { Query query = Query.query(Criteria.where("name").regex(name)); mongoTemplate.remove(query, User.class); } /** * * @description 删除user元素中hobby属性数组元素的开头或者结尾,根据参数而定 * @param name */ @Override public void deleteArrFirst(String name) { Query query = Query.query(Criteria.where("name").is(name)); Update update = new Update(); update.pop("hobby", Position.FIRST); mongoTemplate.updateFirst(query, update, User.class); update.pop("hobby", Position.LAST); mongoTemplate.updateFirst(query, update, User.class); } /** * @description 根据hobby数组的具体对象值,删除对象的数组数据 * @param name 行数据名称 * @param key 数组键 * @param value 数组值 */ @Override public void pullDomArray(String name,String key, String value) { Query query = new Query(); query.addCriteria(Criteria.where("name").is(name)); Update update = new Update(); update.pull(key, value); mongoTemplate.updateFirst(query, update, User.class); } }