1、引入驱动包
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.10.2</version>
</dependency>
备注:非maven项目
2、连接数据库
//不认证 默认值 localhost 27017
MongoClient mongoClient1 = new MongoClient("192.168.244.132", 27017);
//默认认证机制,需要开启认证机制
MongoCredential credential = MongoCredential.createCredential("admin", "wuhan", "123456".toCharArray());
MongoClient mongoClient2 = new MongoClient(new ServerAddress("192.168.244.132", 27017),Arrays.asList(credential));
//使用连接字符串而不明确指定认证机制,需要开启认证机制
MongoClientURI uri = new MongoClientURI("mongodb://admin:123456@192.168.244.132/?authSource=wuhan");
MongoClient mongoClient = new MongoClient(uri);
3、CRUD操作
//获取集合
MongoCollection<Document> collection = database3.getCollection("wuhan");
//插入一个文档
Document document = new Document("T_TargetID","MMC8000GPSANDASYN051113-24806-00000000")
.append("T_Time", "2016-06-29 23:59:59")
.append("T_UTCTime", 1404143999)
.append("T_Longitude", 114.392766)
.append("T_Latitude", 30.469206)
.append("T_Speed", 11.233611)
.append("T_Heading", 321.47);
collection.insertOne(document);
//插入多个文档
List<Document> list = new ArrayList<>();
for(int i = 1; i <= 3; i++) {
Document document1 = new Document("T_TargetID","MMC8000GPSANDASYN051113-24806-00000000")
.append("T_Time", "2016-06-29 23:59:59")
.append("T_UTCTime", 1404143999)
.append("T_Longitude", 114.392766)
.append("T_Latitude", 30.469206)
.append("T_Speed", 11.233611)
.append("T_Heading", 321.47);
list.add(document1);
}
collection.insertMany(list);
//申明条件
Bson filter = Filters.eq("T_Time","2016-06-29 23:59:59");
//指定修改的更新文档
Document update = new Document("$set", new Document("T_Speed", 120));
//修改单个文档
collection.updateOne(filter, update);
//修改多个文档
collection.updateMany(filter, update);
//删除与筛选器匹配的单个文档
collection.deleteOne(filter);
//删除与筛选器匹配的所有文档
collection.deleteMany(filter);
//查找集合中的所有文档
FindIterable findIterable = collection.find();
MongoCursor<Document> cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
//指定查询过滤器查询
FindIterable findIterable2 = collection.find(filter);
MongoCursor<Document> cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
//添加过滤条件查询
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = format.parse("2016-06-29 23:59:59");
// 组装文档
BasicDBObject searchDoc = new BasicDBObject().append("T_Time", date);
// 组装文档,并设置条件,大于:$gt,大于等于:$gte,小于:$lt,小于等于:$lte,不等于:$ne
//BasicDBObject searchDoc = new BasicDBObject().append("T_Time", new Document().append("$lt", date));
// 进行查询并限制查询条数
FindIterable<Document> findIterable = collection.find(searchDoc).limit(10);
//进行查询并排序
//FindIterable<Document> find = collection.find(searchDoc).sort(new Document().append("T_Time", -1)).limit(10);
MongoCursor<Document> cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}