MongoTemplate使用
package com.yyd.web.ssm.entity;
import com.alibaba.fastjson.JSONArray;
import org.springframework.data.mongodb.core.mapping.Document;
/***
* @ClassName: MongoEntity
* @Description: TODO
* @author: yanyd
* @Date: 14:25 2020/4/18
* @version : V1.0
*/
@Document(collection = "def_mongo")
public class MongoEntity {
private String age;
private String name;
private String sex;
private Double num;
private String birth;
private JSONArray arr;
public Double getNum() {
return num;
}
public void setNum(Double num) {
this.num = num;
}
public JSONArray getArr() {
return arr;
}
public void setArr(JSONArray arr) {
this.arr = arr;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
}
package com.yyd.web.ssm;
import com.alibaba.fastjson.JSON;;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.DBObject;
import com.yyd.web.ssm.entity.MongoEntity;
import com.yyd.web.ssm.webUtils.mongodb.MongoDBClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
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 java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
/***
* @ClassName: MongoTest
* @Description: TODO
* @author: yanyd
* @Date: 14:05 2020/4/18
* @version : V1.0
*/
public class MongoTest {
private static Logger LOGGER = LoggerFactory.getLogger(MongoTest.class);
private static MongoDBClient mongoDBClient = new MongoDBClient();
private static MongoTemplate mongoTemplate = mongoDBClient.getMongoTemplate();
// db.getCollection('db1').update({},{"$addToSet":{"info":{"$each": [ {"d":"c"}, {"d":"a"},{"d":"b"} ] ,"$sort": { "d": 1 }, "$slice": 3}}},false,true) //$push有重复值
// db.getCollection('db1').update({},{"$pull":{"info":{"$in": [ {"d":"d"},9240] }}},false,true)
public static void main(String[] args) {
pull();
}
public static void insert() {
//insert
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
MongoEntity mongoEntity = new MongoEntity();
mongoEntity.setAge("18");
mongoEntity.setName("test");
mongoEntity.setSex("M");
mongoEntity.setNum(1.2);
mongoEntity.setBirth(simpleDateFormat.format(new Date()));
mongoTemplate.save(mongoEntity);
}
public static void query_and() {
//and
Query query = new Query();
query.addCriteria(new Criteria("name").regex("test"));
query.addCriteria(new Criteria("birth").gte("2020-04-19 14:34:50").lte("2020-04-22 13:34:50"));
query.addCriteria(new Criteria("age").in(new String[]{"18", "19", "20"}));
query.addCriteria(new Criteria("num").is(1.2));
List<MongoEntity> mongoEntityList = mongoTemplate.find(query, MongoEntity.class);
LOGGER.info(JSON.toJSONString(mongoEntityList));
}
public static void query_or() {
//or
Query query = new Query();
query.addCriteria(new Criteria().orOperator(new Criteria("name").is("test"), new Criteria("name").is("test1")));
query.addCriteria(new Criteria("age").is("18"));
List<MongoEntity> mongoEntityList = mongoTemplate.find(query, MongoEntity.class);
LOGGER.info(JSON.toJSONString(mongoEntityList));
}
public static void query_sort_skip_limit() {
//query_sort_skip_limit
Query query = new Query();
query.addCriteria(new Criteria("name").regex("test"));
query.with(new Sort(new Sort.Order(Sort.Direction.ASC, "birth")));
query.skip(0);
query.limit(1);
List<MongoEntity> mongoEntityList = mongoTemplate.find(query, MongoEntity.class);
LOGGER.info(JSON.toJSONString(mongoEntityList));
}
public static void update() {
//update
Update update = new Update();
update.set("param", "param1");
mongoTemplate.updateFirst(new Query().addCriteria(new Criteria("name").is("test2")), update, MongoEntity.class);
}
public static void push_addSet() {
//push_addSet
Update update = new Update();
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("k1", "v");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("k2", "v");
jsonArray.add(jsonObject);
jsonArray.add(jsonObject1);
//拆分插入
//update.addToSet("param1").each(jsonArray);
//直接插入数组
update.addToSet("param1", jsonArray);
mongoTemplate.updateFirst(new Query().addCriteria(new Criteria("name").is("test2")), update, MongoEntity.class);
}
public static void pull() {
//pull
Update update = new Update();
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("k1", "v");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("k2", "v");
jsonArray.add(jsonObject);
jsonArray.add(jsonObject1);
update.pull("param1", jsonArray);
mongoTemplate.updateFirst(new Query().addCriteria(new Criteria("name").is("test2")), update, MongoEntity.class);
}
public static void aggregate() {
//aggregate
Aggregation customerAgg = Aggregation.newAggregation(
Aggregation.project("name", "age", "sex", "birth", "num", "arr"),
Aggregation.match(new Criteria("name").regex("test")),
Aggregation.unwind("arr"),
Aggregation.group("name", "age")
.sum("num").as("num")//统计sum总数
.count().as("count")//统计按 name,age分组的个数
.addToSet("num").as("num_addToSet")//将每组的num字段数据添加到num_addToSet数组中 并去重
.push("num").as("num_push")//将每组的num字段数据添加到num_addToSet数组中 不去重
.first("num").as("num_first")//显示每组第一条数据的num字段数据
.last("num").as("num_last")//显示每组最后一条数据的num字段数据
.min("num").as("num_min")//显示每组数据最小的num字段数据
.max("num").as("num_max"),//显示每组数据最大的num字段数据
Aggregation.sort(new Sort(new Sort.Order(Sort.Direction.ASC, "num"))),
Aggregation.skip(0L),
Aggregation.limit(100L)
);
AggregationResults<DBObject> aggregationResults = mongoTemplate.aggregate(customerAgg, MongoEntity.class, DBObject.class);
Iterator<DBObject> iterator = aggregationResults.iterator();
while (iterator.hasNext()) {
DBObject dbObject = iterator.next();
LOGGER.info(dbObject.toMap().toString());
}
}
}
//多个$and $or的情况
Query query = new Query();
Criteria[] list=new Criteria[2];
Criteria criteria = new Criteria().andOperator(new Criteria("age").is("test"), new Criteria("age").is("test1"));
list[0]=criteria;
list[1]=criteria;
query.addCriteria(new Criteria().andOperator(list));
System.out.println(query.toString());
List<MongoEntity> mongoEntityList = mongoTemplate.find(query, MongoEntity.class);
log.info(JSON.toJSONString(mongoEntityList));
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.10.15.RELEASE</version>
</dependency>
网友评论