准备
首先就是导入jar包,mongo-java-driver-3.4.3.jar
Utils
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package Utils; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoDatabase; import java.util.ArrayList; import java.util.List; //mongodb 连接数据库工具类 public class MongoDBUtil { //不通过认证获取连接数据库对象 public static MongoDatabase getConnect(String dbs){ //连接到 mongodb 服务 MongoClient mongoClient = new MongoClient("localhost", 27017); //连接到数据库 MongoDatabase mongoDatabase = mongoClient.getDatabase(dbs); //返回连接数据库对象 return mongoDatabase; } //需要密码认证方式连接 public static MongoDatabase getConnect2(){ List<ServerAddress> adds = new ArrayList<>(); //ServerAddress()两个参数分别为 服务器地址 和 端口 ServerAddress serverAddress = new ServerAddress("localhost", 27017); adds.add(serverAddress); List<MongoCredential> credentials = new ArrayList<>(); //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码 MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray()); credentials.add(mongoCredential); //通过连接认证获取MongoDB连接 MongoClient mongoClient = new MongoClient(adds, credentials); //连接到数据库 MongoDatabase mongoDatabase = mongoClient.getDatabase("test"); //返回连接数据库对象 return mongoDatabase; } } |
utils中有两种方式,一种是无密码, 一种是带密码的,我一般都是无密码的连接,然后主函数中这样写:
1 |
MongoCollection<Document> collection = MongoDBUtil.getConnect("zy_stu").getCollection("student_course"); |
非常的方便,zy_stu表示数据库,student_course表示集合
增删改查
新增数据
1 2 3 4 5 6 7 8 |
public void test1(){ Document document = new Document("name","张三").append("age",18); // 插入一个文档 collection.insertOne(document); // 插入多个文档 List<Document> list = new ArrayList<>(); collection.insertMany(list); } |
基本思路就是Document构造文档,然后使用collection中的insert方法
删除数据
1 2 3 4 5 6 |
@Test public void delete(){ //要记住collection是一个集合,不是连接,连接的英文是connection Bson filter = Filters.eq("name", "张三"); collection.deleteOne(filter); } |
修改数据
1 2 3 4 5 6 7 |
public void update(){ Object value; Bson f = Filters.eq("name", "张三"); Document document = new Document("$set",new Document("name","李四")); collection.updateOne(f, document); } |
查询数据
1 2 3 4 5 6 7 8 9 10 11 |
public void select(){ FindIterable findIterable = collection.find(); MongoCursor cursor = findIterable.iterator(); System.out.println(cursor); List list = new ArrayList<>(); while(cursor.hasNext()){ Document document = (Document) cursor.next(); list.add(document.toJson()); } System.out.println(list); } |
除了新增,其他操作基本都需要一个过滤器Bson f = Filters.eq(“name”, “张三”);没啥好说的,查询的话,使用cursor拿到迭代器的游标,然后使用Document接收游标的next()方法,之后对document进行处理得到自己想要的数据。Document中自带转为json的方法
聚合查询
聚合查询应该是使用最多的操作,思路也很简单,就是构造Document,和mongodb本身的聚合查询一模一样。
这里根据,SID学号进行分组,然后返回想要的聚合数据avg平均分数SCORE,也就是分组的目的。然后使用sort进行排序,最后limit得到平均分最高的前十个学生。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
public class TestGroup { MongoCollection<Document> collection = MongoDBUtil.getConnect("zy_stu").getCollection("student_course"); @Test public void test1(){ //使用聚合查询 List<Document> aggregateList = new ArrayList<>(); Document sub_group = new Document(); sub_group.put("_id","$SID"); sub_group.put("avg_score",new Document("$avg","$SCORE")); Document sub_sort = new Document(); sub_sort.put("avg_score",-1); Document group = new Document("$group",sub_group); Document sort = new Document("$sort",sub_sort); Document limit = new Document("$limit",10); aggregateList.add(group); aggregateList.add(sort); aggregateList.add(limit); System.out.println(aggregateList); JSONObject ret_obj = new JSONObject(); AggregateIterable<Document> aggregateIterable = collection.aggregate(aggregateList); MongoCursor<Document> cursor = aggregateIterable.iterator(); List<String> list = new ArrayList<>(); try { while(cursor.hasNext()) { Document document = cursor.next(); list.add(document.toJson()); // System.out.println(cursor.next()); // list.add(document.toJson()); } } finally { cursor.close(); } System.out.println(list); } } |
一些坑
mongodb的查询,更新操作都是区别数据类型的,数值一样,但是Double和String的话是不可能找得到的。看下面这个代码:
1 |
Double SCORE = Double.parseDouble(request.getParameter("SCORE")); |
必要的时候,在接收前端一些数据时进行处理一下