标签:
下面是mongoDb简单的增删改查(新闻类)
附:query.addCriteria(Criteria.where("modelId").ne("").ne(null)); //非空
query.with(new Sort(new Order(Direction.DESC, "ct"))); //倒叙
多个字段排序:第一排序按照sort降序,第二排序按照ct降序
query.with(new Sort(new Order(Direction.DESC, "sort")).and(new Sort(Direction.DESC,"ct")));
public class NewsHelpService { @Resource private MongoTemplate mongoTemplate; //add public void insert(NewsHelp newsHelp) { mongoTemplate.insert(newsHelp); } //select public Pagination<NewsHelp> findNewsHelpAll(String type, String title, String id, Integer pageNo, Integer pageSize) { // QueryPage page = QueryPage.build(pageNo, pageSize); MandoAssert.notNull(type, "类型不能为空"); Criteria criteria = Criteria.where("type").is(type); if (title!=null) { Pattern pattern = Pattern.compile(title, Pattern.CASE_INSENSITIVE); //模糊查询 criteria.andOperator(Criteria.where("title").regex(pattern)); } if (id!=null) { criteria.andOperator(Criteria.where("id").is(id)); } Query query = BasicQuery.query(criteria); long total = mongoTemplate.count(query, NewsHelp.class); Pagination<NewsHelp> newsHelps = new Pagination<NewsHelp>(pageNo, pageSize); int skip = (pageNo-1)*pageSize; if (pageSize<1) { query.skip(skip);// skip相当于从那条记录开始 query.limit(pageSize);// 从skip开始,取多少条记录 } List<NewsHelp> datas = mongoTemplate.find(query, NewsHelp.class); newsHelps.setData(datas);//获取数据 newsHelps.setTotal((int)total); return newsHelps; } //selectOne public NewsHelp findNewsHelp(String id) { Query query = BasicQuery.query(Criteria.where("id").is(id)); NewsHelp newsHelp = mongoTemplate.findOne(query, NewsHelp.class); return newsHelp; } // update 新闻类 public void updateNewsHelp(NewsHelp help) { MandoAssert.notNull(help.getId(), "ID不能为空"); Update update = new Update(); if(null!=help.getTops()){ update.set("tops", help.getTops()); } if(StringUtils.isNotEmpty(help.getTitle())){ update.set("title", help.getTitle()); } if(StringUtils.isNotEmpty(help.getContent())){ update.set("content", help.getContent()); } update.set("modifyDate", new Date()); mongoTemplate.updateMulti(Query.query(Criteria.where("id").is(help.getId())),update,NewsHelp.class); } //delete public void delNewsHelp(List<String> ids) { ids.stream().forEach(id -> { Query query = BasicQuery.query(Criteria.where("id").is(id)); mongoTemplate.findAndRemove(query, NewsHelp.class); }); } }
偶遇晨光原创
下面讲解一下springMVC+mongodb配置
标签:
原文地址:http://www.cnblogs.com/chenyq/p/5416310.html