2021年07月30日 | Wizzer | 评论 采用最新Java驱动 <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.3.0</version> </dependency> 获取数据源及数据库 /** * @author wizzer@qq.com */ public class ZMongoDatabase { private MongoDatabase db; public ZMongoDatabase(MongoDatabase db) { this.db = db; } /** * 获取集合,集合不存在则返回 null * * @param name 集合名称 * @return 集合薄封装 */ public MongoCollection<Document> getCollection(String name) { if (!this.collectionExists(name)) { return null; } return db.getCollection(name); } /** * 获取一个集合,如果集合不存在,就创建它 * * @param name 集合名 * @param dropIfExists true 如果存在就清除 * @return 集合薄封装 */ public MongoCollection<Document> createCollection(String name, boolean dropIfExists) { // 不存在则创建 if (!this.collectionExists(name)) { return createCollection(name, null); } // 固定清除 else if (dropIfExists) { db.getCollection(name).drop(); return createCollection(name, null); } // 已经存在 return db.getCollection(name); } /** * 获取一个集合,如果集合不存在,就创建它 * * @param name 集合名 * @param options 集合配置信息 * @param dropIfExists true 如果存在就清除 * @return 集合薄封装 */ public MongoCollection<Document> createCollection(String name, CreateCollectionOptions options, boolean dropIfExists) { // 不存在则创建 if (!this.collectionExists(name)) { return createCollection(name, options); } // 固定清除 else if (dropIfExists) { db.getCollection(name).drop(); return createCollection(name, options); } // 已经存在 return db.getCollection(name); } /** * 创建一个集合 * * @param name 集合名 * @param options 集合配置信息 * @return 集合薄封装 */ public MongoCollection<Document> createCollection(String name, CreateCollectionOptions options) { if (this.collectionExists(name)) { throw Lang.makeThrow("Colection has exists: %s.%s", db.getName(), name); } // 创建默认配置信息 if (null == options) { options = new CreateCollectionOptions().capped(false); } db.createCollection(name, options); return db.getCollection(name); } /** * 判断集合是否存在 * * @param collectionName 集合名 * @return */ public boolean collectionExists(String collectionName) { return listCollectionNames().contains(collectionName); } /** * @return 当前数据库所有可用集合名称 */ public List<String> listCollectionNames() { return db.listCollectionNames().into(new ArrayList<String>()); } public MongoDatabase getNativeDB() { return this.db; } } 初始化数据库示例 @Inject private ZMongoDatabase zMongoDatabase; public void init() { CreateCollectionOptions collectionOptions = new CreateCollectionOptions(); TimeSeriesOptions timeSeriesOptions = new TimeSeriesOptions("ts"); timeSeriesOptions.metaField("metadata"); timeSeriesOptions.granularity(TimeSeriesGranularity.SECONDS); collectionOptions.timeSeriesOptions(timeSeriesOptions); MongoCollection<Document> deviceCollection = zMongoDatabase.createCollection("device", collectionOptions, true); List<Document> list = new ArrayList<>(); Device device = new Device(Times.now(), 36.7, "0001"); list.add(new Document().append("ts", device.getTs()).append("temperature", device.getTemperature()).append("metadata", new Document().append("no", device.getNo()))); Device device1 = new Device(Times.now(), 35.2, "0002"); list.add(new Document().append("ts", device1.getTs()).append("temperature", device1.getTemperature()).append("metadata", new Document().append("no", device1.getNo()))); Device device2 = new Device(Times.now(), 10.7, "0002"); list.add(new Document().append("ts", device2.getTs()).append("temperature", device2.getTemperature()).append("metadata", new Document().append("no", device2.getNo()))); Device device3 = new Device(Times.nextDay(Times.now(), 1), 30.0, "0002"); list.add(new Document().append("ts", device3.getTs()).append("temperature", device3.getTemperature()).append("metadata", new Document().append("no", device3.getNo()))); // Document.parse(Json.toJson(new Device())); InsertManyResult insertManyResult = deviceCollection.insertMany(list); log.info(Json.toJson(insertManyResult)); } 时序数据求平均值示例 // 官方时序数据统计Demo https://docs.mongodb.com/manual/core/timeseries-collections/ @Ok("json:full") @At("/avg") public Object avg(@Param(value = "no", df = "0002") String no) { List<Bson> bsons = new ArrayList<>(); // 筛选条件 Bson match = Aggregates.match(Filters.eq("metadata.no", no)); // 输出对象 Bson project = Aggregates.project(Projections.fields( // 日期格式化 Projections.computed("date", new Document("$dateToParts", new Document().append("date", "$ts"))), Projections.computed("temperature", 1) )); // 分组统计 平均值 Bson group = Aggregates.group(new Document("date", new Document().append("year", "$date.year").append("month", "$date.month").append("day", "$date.day")), Accumulators.avg("avgTemp", "$temperature") ); bsons.add(match); bsons.add(project); bsons.add(group); log.info(Json.toJson(bsons)); return zMongoDatabase.getCollection("device").aggregate(bsons); } 完整代码: nutzboot starter 组件 nutzboot-starter-mongodb-plus 组件使用示例 nutzboot-demo-simple-mongodb-plus i’am a separator… 1,063 total views, 7 views today