依赖
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
MongoDB在SpringBoot中的配置
@Component
public class MongoConfig {
private String db;
private MongoDatabase mongoDatabase;
private MongoClient client;
@Value("${mongodb.url}")
private String mongoDbUrl;
//刚启动程序的初始化
@PostConstruct
public boolean init() {
try {
MongoClientURI uri = new MongoClientURI(mongoDbUrl);
this.db = uri.getDatabase();
client = new MongoClient(uri);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return initDatabaseAndCollections();
}
public boolean initDatabaseAndCollections() {
if (initDatabase()) {
return true;
}
return false;
}
public MongoConfig() {
}
public boolean initDatabase() {
ListDatabasesIterable<Document> iterable = client.listDatabases();
Iterator<Document> iterator = iterable.iterator();
while (iterator.hasNext()) {
Document document = iterator.next();
String database = (String) document.get("name");
if (database != null && database.equals(db)) {
mongoDatabase = client.getDatabase(db);
return true;
}
}
return false;
}
public MongoCollection getCollection(String collectionName){
return mongoDatabase.getCollection(collectionName);
}
public void close() {
if (client != null) {
client.close();
}
}
}
方法
@Repository
public class CustomerTreeDaoImpl implements ICustomerTreeDao {
@Autowired
private MongoConfig mongoConfig;
@Override
public List<StatisticDTO> statisticBy(final String group, final String fieldName) {
if (StringUtils.isEmpty(group) || StringUtils.isEmpty(fieldName)) {
return new ArrayList<>(0);
}
final MongoCollection<Document> collection = mongoConfig.getCollection(CUSTOMER_TREE_COLLECTION_NAME);
//查询条件
Bson condition = Filters.and(Filters.eq("group", group));
List<StatisticDTO> statistic = new ArrayList<>();
Block<Document> printBlock = new Block<Document>() {
@Override
public void apply(Document document) {
//document中包括_id,如,通过省份分组的话_id就是省份名称或者是省份代码,根据库中具体的数据而定
//包括分组中的fieldName,这个name中存的就是数值,如果北京有20条数据,那么fieldName对应的值就是20.
final StatisticDTO statisticDTO = new StatisticDTO();
statisticDTO.setKey(document.getString("_id"));
statisticDTO.setValue(document.getLong(fieldName));
statistic.add(statisticDTO);
}
};
//执行聚合操作
collection.aggregate(
Arrays.asList(
//查询条件匹配
Aggregates.match(condition),
//分组,根据fieldName分组,“$”符号必须添加
Aggregates.group("$"+fieldName,
Accumulators.sum(fieldName, 1L))
)
).forEach(printBlock);//此处的foreach会循环执行上面printBlock对象中的applay方法
return statistic;
}
}
最后
有缘人,希望这篇博客可以帮助你,点个👍吧