步骤一、从MongoCompass中获取java代码
将java代码复制出来,从MongoCompass中复制的java代码基本格式如下:(是Bson原生格式)
List<Document> list = Arrays.asList( new Document("$match", new Document("name", "小明")), new Document("$sort", new Document("age", -1L)), new Document("$limit", 20L));
步骤二 、在java项目中使用
private List<Person> testCompassJavaExport() {
AggregateIterable<Document> aggregate = mongoTemplate.getCollection("person").aggregate(queryList, Document.class);
List<Person> resultList = new ArrayList<>();
aggregate.forEach(p -> {
Person dto = JsonUtils.jsonToObject(p.toJson(), Person.class);
resultList.add(dto);
});
return resultList;
}
// JsonUtils.java
public class JsonUtils {
public static <T> T jsonToObject(String json, Class<T> clazz) {
T ret = null;
if (StringUtils.isNotBlank(json)) {
try {
ret = getObjectMapper().readValue(json, clazz);
} catch (IOException var4) {
LOGGER.error("Json {} to object failed!", json, var4);
}
}
return ret;
}
}