1. 配置文件
pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.11.2</version>
</dependency>
<dependency>
<groupId>org.jongo</groupId>
<artifactId>jongo</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.7</version>
</dependency>
<dependencies>
yml
server:
port: 80
jongo:
host: localhost
port: 27017
database: curd
2.Jongo常用方法
save(Object o)
新增
insert(Object o)
新增
insert(Object... o)
新增
remove()
删除集合全部内容
remove(ObjectId)
根据Id删除
remove(String query)
根据条件删除
remove(String query ,Object o)
根据条件删除
find()
查询全部
find(String query)
根据条件查询
find(String query ,Object o)
根据条件查询
findOne()
查询一条
findOne(String query)
根据条件查询一条
findOne(String query ,Object o)
根据条件查询一条
update(ObjectId id)
根据Id修改
update(String query, Object... parameters)
根据条件修改
aggregate(String pipelineOperator)
聚合查询
aggregate(String pipelineOperator, Object... parameters)
聚合查询
3.代码
annotation
用于反射获取集合名称
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Document {
@AliasFor("collection")
String value() default "";
@AliasFor("value")
String collection() default "";
}
config
@Configuration
@ConfigurationProperties(prefix = "jongo")
@Data
public class JongoConfig {
private String host;
private Integer port;
private String database;
}
dao
@Repository
public abstract class BaseDAO<T> {
private Class<T> clazz;
private MongoCollection mongoCollection;
@Autowired
private JongoConfig jongoConfig;
public BaseDAO() {
clazz = getSuperClassGenericType();
}
private Class getSuperClassGenericType() {
Type type = this.getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
clazz = (Class<T>) parameterizedType.getActualTypeArguments()[0];
}
return clazz;
}
@Bean
protected MongoCollection getCollection() {
String collectionName = clazz.getSimpleName().toLowerCase();
if (clazz.isAnnotationPresent(Document.class)) {
Document annotation = clazz.getAnnotation(Document.class);
collectionName = annotation.collection();
}
Jongo jongo = new Jongo(new MongoClient(jongoConfig.getHost(), jongoConfig.getPort()).getDB(jongoConfig.getDatabase()));
mongoCollection = jongo.getCollection(collectionName);
return mongoCollection;
}
public WriteResult save(Object o) {
WriteResult save = mongoCollection.save(o);
return save;
}
public WriteResult insert(Object o) {
WriteResult insert = mongoCollection.insert(o);
return insert;
}
public WriteResult insert(Object... o) {
WriteResult insert = mongoCollection.insert(o);
return insert;
}
public WriteResult delete() {
WriteResult remove = mongoCollection.remove();
return remove;
}
public WriteResult delete(String id) {
WriteResult remove = mongoCollection.remove(new ObjectId(id));
return remove;
}
public WriteResult delete(String query, Object... o) {
WriteResult remove = mongoCollection.remove(query, o);
return remove;
}
public List<T> find() {
MongoCursor<T> as = mongoCollection.find().as(clazz);
return toList(as);
}
public List<T> find(String query, Object... o) {
MongoCursor<T> as = mongoCollection.find(query, o).as(clazz);
return toList(as);
}
public T findOne() {
T as = mongoCollection.findOne().as(clazz);
return as;
}
public T findOne(String query, Object... o) {
T as = mongoCollection.findOne(query, o).as(clazz);
return as;
}
public WriteResult update(String id, T t) {
WriteResult update = mongoCollection.update(new ObjectId(id)).with(t);
return update;
}
public WriteResult update(String query, T t, Object... o) {
WriteResult update = mongoCollection.update(query, o).with(t);
return update;
}
public WriteResult updateMulti(String query, T t, Object... o) {
WriteResult update = mongoCollection.update(query, o).multi().with(t);
return update;
}
public Aggregate aggregate(String pipelineOperator) {
Aggregate aggregate = mongoCollection.aggregate(pipelineOperator);
return aggregate;
}
protected List<T> toList(MongoCursor mongoCursor) {
List<T> list = new ArrayList<>();
while (mongoCursor.hasNext()) {
Object next = mongoCursor.next();
list.add((T) next);
}
return list;
}
protected <R> List<R> toList(Aggregate.ResultsIterator<R> resultsIterator) {
List<R> list = new ArrayList<>();
while (resultsIterator.hasNext()) {
R next = (R) resultsIterator.next();
list.add(next);
}
return list;
}
}
@Repository
public class UserDAO extends BaseDAO<User> {
}
model
@Data
@Document(collection = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@MongoObjectId
private String _id;
private String username;
private String password;
private String nickName;
private Integer age;
private List<String> address;
}
@Data
public class UserResVO implements Serializable {
private static final long serialVersionUID = 1L;
@MongoObjectId
private String _id;
private List<String> username;
private List<String> nickName;
private Integer count;
}
4.测试用例
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class UserDAOTest {
@Autowired
UserDAO userDAO;
@Test
public void saveTest() {
List<User> collect = IntStream.range(0, 100).mapToObj(num -> {
User user = new User();
user.setAge(18);
user.setNickName("超级好看");
user.setUsername("张三" + num);
user.setPassword("123456");
return user;
}).collect(Collectors.toList());
WriteResult save = userDAO.insert(collect);
log.info("saveTest : {}", save);
}
@Test
public void insertTest() {
User user = new User();
user.setAge(18);
user.setNickName("超级好看");
user.setUsername("张三");
user.setPassword("123456");
WriteResult insert = userDAO.insert(user);
log.info("insertTest : {}", insert);
}
@Test
public void insertTest2() {
IntStream.range(0, 100).forEach(n -> {
User user = new User();
user.setAge(18);
user.setNickName("超级好看");
user.setUsername("张三" + n);
user.setPassword("123456");
userDAO.insert(user);
});
}
@Test
public void deleteTest() {
WriteResult remove = userDAO.delete();
log.info("deleteTest : {}", remove);
}
@Test
public void deleteTest2() {
String query = "{ " +
"username : { $regex : #}" +
"}";
WriteResult remove = userDAO.delete(query, "^张三");
log.info("deleteTest : {}", remove);
}
@Test
public void findOneTest() {
String query = "{ username : # }";
User lis = userDAO.findOne(query, "lis");
log.info("findOneTest : {}", lis);
}
@Test
public void findTest() {
String query = "{ " +
"username : { $regex : #}" +
"}";
List<User> users = userDAO.find(query, "^张三");
log.info("length : {} ,findTest : {}", users.size(), users);
}
@Test
public void updateTest() {
User one = userDAO.findOne();
log.info("updateTest one :{}", one);
User user = new User();
user.setAge(19);
WriteResult update = userDAO.update(one.get_id(), user);
log.info("updateTest update:{}", update);
}
@Test
public void updateTest2() {
User user = new User();
user.setAge(20);
String query = "{ age : { $gte : # } }";
WriteResult update = userDAO.update(query, user, 18);
log.info("updateTest2 update:{}", update);
}
@Test
public void updateMultiTest() {
User user = new User();
user.setAge(18);
String query = "{ age : { $gte : # } }";
WriteResult update = userDAO.updateMulti(query, user, 18);
log.info("updateMultiTest update:{}", update);
}
@Test
public void aggregateTest() {
String match = "{ $match : { nickName: { $regex : '好看$' }, age : { $gte : 16, $lte : 18 } } }";
String group = "{ $group : { _id: '$_id', username : { $push : '$username'}, nickName : { $push : '$nickName' }, count : { $sum : 1 } } }";
Aggregate.ResultsIterator<UserResVO> as = userDAO.aggregate(match).and(group).as(UserResVO.class);
List<UserResVO> users = userDAO.toList(as);
log.info("length: {} ,aggregateTest:{}", users.size(), users);
}
}
5.小练习
model
@Document(collection = "favorite_unit")
@Data
public class FavoriteUnit implements Serializable {
private static final long serialVersionUID = 1L;
private String _id;
private String agentId; //代理人ID
private String unitId; //单元ID
private Date createTime;//创建时间
}
题目:获取上个月某个代理人添加的unitId列表和对应unitId的添加次数
答案
db.getCollection("favorite_unit").aggregate([
{ $match : {
createTime : {
$gt : ISODate("2020-06-01"),
$lt : ISODate("2020-07-01")
},
agentId : "5c1cacc718aad600067b7aa0"
},
},
{ $group : { _id:"$unitId",count : {$sum: 1 }} }
])
private Date getDate(LocalDateTime localDateTime) {
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = localDateTime.atZone(zoneId);//Combines this date-time with a time-zone to create a ZonedDateTime.
return Date.from(zdt.toInstant());
}
String agentId = "5c1cacc718aad600067b7aa0";
LocalDateTime localDateTime = LocalDateTime.now().minusMonths(1);
LocalDateTime firstDayOfMonth = localDateTime.with(TemporalAdjusters.firstDayOfMonth());
firstDayOfMonth = LocalDateTime.of(firstDayOfMonth.toLocalDate(), LocalTime.MIN);
LocalDateTime lastDayOfMonth = localDateTime.with(TemporalAdjusters.lastDayOfMonth());
lastDayOfMonth = LocalDateTime.of(lastDayOfMonth.toLocalDate(), LocalTime.MAX);
String match = "{ $match : { createTime : { $gt : # , $lt : # }, agentId : # } }";
String group = "{ $group : { _id:'$unitId',count : {$sum: 1 } } }";
mongoCollection.aggregate(match, getDate(firstDayOfMonth), getDate(lastDayOfMonth), agentId).and(group).as(FavoriteUnit.class);