坐标,mongo-java-driver
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.0.3</version>
</dependency>
</dependencies>
连接到服务器:
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient("localhost", 27017);
显示与删除数据库:
String DB_NAME = "mydb";
// 显示所有数据库名字
mongoClient.listDatabaseNames().forEach((Block<String>) name -> {
System.out.println("DB_NAME: " + name);
if (name.equals(DB_NAME)) {
mongoClient.dropDatabase(DB_NAME);
System.out.println("DB " + name + " DROPPED ======================");
}
});
连接到数据库:
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
创建与获取集合
String DB_COL = "mycol";
// 创建集合
mongoDatabase.createCollection(DB_COL);
// 获取集合
MongoCollection mongoCollection = mongoDatabase.getCollection(DB_COL);
插入文档:
//插入文档
Document document = new Document("title", "MongoDB").append("description", "database").append("likes", 100);
List<Document> documents = new ArrayList<>();
documents.add(document);
documents.add(new Document("title", "HBase").append("description", "database2").append("likes", 90));
documents.add(new Document("title", "Redis").append("description", "database3").append("likes", 80));
mongoCollection.insertMany(documents);
更新文档:
// 更新文档
mongoCollection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));
删除文档:
// 删除符合条件的第一个文档
mongoCollection.deleteOne(Filters.eq("likes", 80));
// 删除所有符合条件的文档
// mongoCollection.deleteMany (Filters.eq("likes", 80));
查看文档:
// 查看所有文档
mongoCollection.find().forEach(((Block<Document>) doc -> System.out.println(doc)));
// OR view collections like this way
// FindIterable<Document> findIterable = mongoCollection.find();
// MongoCursor<Document> mongoCursor = findIterable.iterator();
// while(mongoCursor.hasNext()){
// System.out.println(mongoCursor.next());
// }
mongoClient.close();
注意,mongodb的数据,类型不严格,而java严谨,比如数据某个值为double,而另一个为string,此时java就有可能报错:
// 条件查询 查询浏览量 大于 1000 的记录
BasicDBObject gtObject = new BasicDBObject("visits", new BasicDBObject("$gt", 1000));
FindIterable<Document> gtFilterFind = spit.find(gtObject);
// 展示查询结果
for (Document doc : gtFilterFind) {
System.out.println("_id: " + doc.get("_id"));
System.out.println("content: " + doc.getString("content"));
System.out.println("userid: " + doc.getString("userid"));
System.out.println("nickname: " + doc.getString("nickname"));
System.out.println("--------------------------------------------");
}
// 关闭连接
client.close();
以上就是java简单操作mongodb的全部内容了。