Java操作MongoDB数据库CRUD(增删查改)
借助mongo-java-driver包,对MongoDB数据库的集合(DataTable)及文档(BSON对象数据)进行增删查改操作。本文的核心在于查询操作,善用mongo-java-driver包下的Iterable迭代器、fing()方法、aggregate()方法,理解Document对象映射BSON对象的底层实现,可完成类似窗口命令行下javascript代码操作MongoDB数据库的所有查询。
1. 环境搭建
1.1 创建项目
本文是在Idea编辑器Maven环境下创建quickstart项目。
1.2 添加依赖
引入junit测试单元,可方便测试代码;
引入MongoDB驱动包,3.9.1版本;
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--MongoDB-->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.9.1</version>
</dependency>
2. 测试环境搭建
2.1 封装MongoDBUtil工具类
此步骤略过,该工具类需具备连接池参数信息的配置,获取MongClient对象及关闭mongoClient功能。
2.2 准备junit测试代码,并测试连接
ongoClient mongoClient = null;
@Before
public void testInit() {
// 获取连接
mongoClient = MongoDBUtil.getMongoClient();
}
@After
public void testClose() {
MongoDBUtil.close(mongoClient);
}
@Test
public void testDB() {
// 连接数据库,存在选中,不存在创建
MongoDatabase db = mongoClient.getDatabase("myDB");
// 删除数据库
mongoClient.dropDatabase("myDB");
}
3. 数据库CRUD(增删查改)操作
3.1 创建集合
集合既是关系型数据库的表。
@Test
public void testCreate(){
//1.’连接数据库,若存在即选中,若不存在就建立
MongoDatabase mongoDatabase = mongoClient.getDatabase("javadb");
//创建集合,此步骤若创建已存在集合,将会报错
//mongoDatabase.createCollection("javaTset");
//2.获取集合,若存在即选中,若不存在就建立
MongoCollection mongoCollection = mongoDatabase.getCollection("javaTset");
//3.获取集合中文档个数
Long collectionSize = mongoCollection.countDocuments();
System.out.println("javadb集合中文档个数:"+collectionSize);
//3.获取整个数据库下集合名称列表
MongoIterable<String> mongoIterable = mongoDatabase.listCollectionNames();
//4.获取迭代器,并遍历
MongoCursor<String> mongoCursor = mongoIterable.iterator();
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next());
}
mongoCursor.close();
//5.删除当前集合
mongoCollection.drop();
}
结果:
javadb集合中文档个数:5
emp
javadb
user
3.2 创建文档
文档既是关系型数据库的row,java代码中由Document(键值对形式,键为字符串,值可以为字符串、数字、Document对象)对象体现,很好的对应了MongoDB中的Bson对象。
@Test
public void testCrud01(){
//连接数据库,存在选中,不存在就建立
MongoDatabase database = mongoClient.getDatabase("javadb");
//获取集合
MongoCollection collection = database.getCollection("javaTest");
//插入一条文档
Document document = new Document();
document.put("name","zhangsan123");
document.put("age",11);
document.put("addr","shanghai");
document.put("date",new Date());
collection.insertOne(document);
//插入多条文档
Document document1 = new Document();
document1.put("name","lisi");
document1.put("age",11);
document1.put("addr","beijing");
document1.put("date",new Date());
Document document2 = new Document();
document2.put("name","wangwu");
document2.put("age",55);
document2.put("addr","guangzhou");
document2.put("date",new Date());
List<Document> list = new ArrayList<>();
list.add(document1);
list.add(document2);
collection.insertMany(list);
//查询所有文档,获取迭代器和游标,并遍历
MongoCursor<Document> cursor = collection.find().iterator();
while (cursor.hasNext()){
System.out.println(cursor.next().toString());
}
cursor.close();
}
结果:
Document{{_id=5c024316b4d5c01d14924040, name=zhangsan123, age=11, addr=shanghai, date=Sat Dec 01 16:15:18 CST 2018}}
Document{{_id=5c024317b4d5c01d14924041, name=lisi, age=11, addr=beijing, date=Sat Dec 01 16:15:19 CST 2018}}
Document{{_id=5c024317b4d5c01d14924042, name=wangwu, age=55, addr=guangzhou, date=Sat Dec 01 16:15:19 CST 2018}}
3.3 更新文档
@Test
public void testCrud03(){
//连接数据库,存在选中,不存在就建立
MongoDatabase database = mongoClient.getDatabase("javadb");
//获取集合
MongoCollection collection = database.getCollection("javaTest");
/**
* 更新操作
*/
//1.获取到要更新的文档
BasicDBObject old = new BasicDBObject();
old.put("name","lisi");
//2.创建更新的文档(需要跟新的字段和值)
BasicDBObject newObj = new BasicDBObject();
newObj.put("age",22);
//3.创建更新操作
BasicDBObject update = new BasicDBObject("$set",newObj);
//4.执行更新
collection.updateOne(old,update);//更新匹配的第一条数据
//collection.updateMany(old,update);//更新多条数据
}
3.4 删除文档
@Test
public void testCrud04() {
//连接数据库,存在选中,不存在就建立
MongoDatabase database = mongoClient.getDatabase("javadb");
//获取集合
MongoCollection collection = database.getCollection("javaTest");
/**
* 删除文档
*/
BasicDBObject obj = new BasicDBObject();
obj.put("name","wangwu");
collection.deleteOne(obj);
}
3.5 查询文档
查询之前需要在MongoDB数据库中新建两个查询源:user、emp,初始化JavaScript代码如下:
//user表
user1 = { "_id":1, "name":"zhangsan","age":1, "hobbies":["music", "read"],"addr":{ "country":"China","city":"BJ" }}
user2 = { "_id":2,"name":"lisi","age":2, "hobbies":["music", "read"],"addr":{"country":"China", "city":"SH"}}
user3 = { "_id":3, "name":"wangwu","age":3,"hobbies":["music", "read"],"addr":{"country":"China","city":"GZ"}}
user4 = {"_id":4,"name":"zhaoliu","age":4,"hobbies":["music", "read"],"addr":{ "country":"China","city":"SZ"}}
user5 = {"_id":5,"name":"tianqi","age":5,"hobbies":["music", "read"],"addr":{"country":"China","city":"TY"}}
db.user.insertMany([user1, user2, user3, user4, user5])
// emp表,练习Aggregate语法,先插入如下数据:
emp1 = {"_id":1,"name":"武大郎","sex":"male","age":18,"hire_date":"20170301","post":"烧饼检察官","salary":7300.33}
emp2 = {"_id":2,"name":"武松","sex":"male","age":78,"hire_date":"20150302","post":"公务员","salary":71000000.31}
emp3 = {"_id":3,"name":"宋江","sex":"male","age":81,"hire_date":"20130305","post":"公务员","salary":78300}
emp4 = {"_id":4,"name":"林冲","sex":"male","age":73,"hire_date":"20140701","post":"公务员","salary":73500}
emp5 = {"_id":5,"name":"林冲","sex":"male","age":73,"hire_date":"20140701","post":"公务员","salary":73500}
emp6 = {"_id":6,"name":"柴进","sex":"male","age":28,"hire_date":"20121101","post":"公务员","salary":72100}
emp7 = {"_id":7,"name":"卢俊义","sex":"female","age":18,"hire_date":"20110211","post":"公务员","salary":79000}
emp8 = {"_id":8,"name":"高俅","sex":"male","age":18,"hire_date":"19000301","post":"公务员","salary":730000}
emp9 = {"_id":9,"name":"鲁智深","sex":"male","age":48,"hire_date":"20101111","post":"公务员","salary":710000}
emp10 = {"_id":10,"name":"史进","sex":"female","age":48,"hire_date":"20150311","post":"打手","salary":73000.13}
emp11 = {"_id":11,"name":"李逵","sex":"female","age":38,"hire_date":"20101101","post":"打手","salary":72000.35}
emp12 = {"_id":12,"name":"周通","sex":"female","age":18,"hire_date":"20110312","post":"打手","salary":71000.37}
emp13 = {"_id":13,"name":"石秀","sex":"female","age":18,"hire_date":"20160513","post":"打手","salary":73000.29}
emp14 = {"_id":14,"name":"李忠","sex":"female","age":28,"hire_date":"20170127","post":"打手","salary":74000.33}
emp15 = {"_id":15,"name":"吴用","sex":"male","age":28,"hire_date":"20160311","post":"文人","salary":710000.13}
emp16 = {"_id":16,"name":"萧让","sex":"male","age":18,"hire_date":"19970312","post":"文人","salary":720000}
emp17 = {"_id":17,"name":"安道全","sex":"female","age":18,"hire_date":"20130311","post":"文人","salary":719000}
emp18 = {"_id":18,"name":"公孙胜","sex":"male","age":18,"hire_date":"20150411","post":"文人","salary":718000}
emp19 = {"_id":19,"name":"朱贵","sex":"female","age":18,"hire_date":"20140512","post":"文人","salary":717000}
db.emp.insertMany([emp1, emp2, emp3, emp4, emp5, emp6, emp7, emp8, emp9, emp10, emp11, emp12, emp13, emp14, emp15, emp16, emp17, emp18, emp19])
条件查询1:匹配查询
@Test
public void testCrud01(){
//连接数据库,存在选中,不存在就建立
MongoDatabase database = mongoClient.getDatabase("javadb");
//获取集合
MongoCollection collection = database.getCollection("user");
/**
* 条件查询1
* 单一字段匹配查询
*/
BasicDBObject obj = new BasicDBObject();
obj.put("name","lisi");
MongoCursor<Document> docs = collection.find(obj).iterator();
while (docs.hasNext()){
System.out.println(docs.next().toString());
}
docs.close();
}
结果:
Document{{_id=6.0, name=lisi, age=42.0, hobbies=[music, read], addr=Document{{country=China, city=SH}}}}
条件查询2:比较、逻辑、投影、排序等查询
@Test
public void testCrud02(){
//连接数据库,存在选中,不存在就建立
MongoDatabase database = mongoClient.getDatabase("javadb");
//获取集合
MongoCollection<Document> collection = database.getCollection("user");
/**
* 条件查询2
*/
System.out.println("查询条件_id==6.0 **************************************");
FindIterable<Document> iterable = collection.find(new Document("_id",6.0));
iterable.forEach(new Block<Document>() {
@Override
public void apply(Document document) {
System.out.println(document.toJson());
}
});
System.out.println("查询条件name == wangwu **************************************");
FindIterable<Document> iterable2 = collection.find(
new Document("name",new Document("$eq","wangwu")));
for (Document doc :iterable2){
System.out.println(doc.toJson());
}
System.out.println("查询条件name != wangwu **************************************");
FindIterable<Document> iterable3 = collection.find(
new Document("name",new Document("$ne","wangwu")));
for (Document doc :iterable3){
System.out.println(doc.toJson());
}
System.out.println("查询条件_id >= 4 **************************************");
FindIterable<Document> iterable4 = collection.find(
new Document("_id",new Document("$gte",4)));
for (Document doc :iterable4){
System.out.println(doc.toJson());
}
System.out.println("查询条件_id <= 4 **************************************");
FindIterable<Document> iterable5 = collection.find(
new Document("_id",new Document("$lte",4)));
for (Document doc :iterable5){
System.out.println(doc.toJson());
}
System.out.println("查询条件_id <=4 && age>60 **************************************");
FindIterable<Document> iterable6 = collection.find(
Filters.and(Filters.lte("_id",4),Filters.gt("age",60)));
for (Document doc :iterable6){
System.out.println(doc.toJson());
}
System.out.println("查询条件_id <=4 || age>60 **************************************");
FindIterable<Document> iterable7 = collection.find(
Filters.or(Filters.lte("_id",4),Filters.gt("age",60)));
for (Document doc :iterable7){
System.out.println(doc.toJson());
}
System.out.println("查询条件_id in 1,3,5 **************************************");
FindIterable<Document> iterable8 = collection.find(
Filters.in("_id",1,3,5));
for (Document doc :iterable8){
System.out.println(doc.toJson());
}
System.out.println("查询条件sort 按年龄排序(升序) **************************************");
FindIterable<Document> iterable9 = collection.find()
.sort(new Document("age",1));
for (Document doc :iterable9){
System.out.println(doc.toJson());
}
System.out.println("查询条件 分页 第二页 每页三条 **************************************");
FindIterable<Document> iterable10 = collection.find()
.limit(3).skip(3);
for (Document doc :iterable10){
System.out.println(doc.toJson());
}
/**
* select name,age from user where id=3;
* db.user.find({'_id':3},{'_id':0,'name':1,'age':1})
*/
System.out.println("查询条件 投影查询 **************************************");
Document document11_1 = new Document();
document11_1.put("_id",3);
Document document11_2 = new Document();
document11_2.put("_id",0);
document11_2.put("name",1);
document11_2.put("age",1);
BasicDBObject object = new BasicDBObject();
Document document11 = new Document();
FindIterable<Document> iterable11 = collection.find(document11_1)
.projection(document11_2);//projection方法查询指定字段
for (Document doc :iterable11){
System.out.println(doc.toJson());
}
}
结果:
查询条件_id==6.0 **************************************
{ "_id" : 6.0, "name" : "lisi", "age" : 42.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "SH" } }
查询条件name==wangwu **************************************
{ "_id" : 3.0, "name" : "wangwu", "age" : 43.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "GZ" } }
{ "_id" : 7.0, "name" : "wangwu", "age" : 43.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "GZ" } }
查询条件name!=wangwu **************************************
{ "_id" : 1.0, "name" : "aaa", "age" : 180.0 }
{ "_id" : 10.0, "name" : "aaa", "age" : 140.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "BJ" } }
{ "_id" : { "$oid" : "5c00e7520af8c80c1ed52c77" }, "name" : "aaa", "age" : 140.0 }
{ "_id" : 6.0, "name" : "lisi", "age" : 42.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "SH" } }
{ "_id" : 5.0, "name" : "tianqi", "age" : 45.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "TY" } }
{ "_id" : 9.0, "name" : "tianqi", "age" : 45.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "TY" } }
{ "_id" : 4.0, "name" : "zhaoliu", "age" : 44.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "SZ" } }
{ "_id" : 8.0, "name" : "zhaoliu", "age" : 44.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "SZ" } }
{ "_id" : 2.0, "name" : "李四", "age" : 60.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "BJ" } }
查询条件_id >=4 **************************************
{ "_id" : 4.0, "name" : "zhaoliu", "age" : 44.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "SZ" } }
{ "_id" : 5.0, "name" : "tianqi", "age" : 45.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "TY" } }
{ "_id" : 6.0, "name" : "lisi", "age" : 42.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "SH" } }
{ "_id" : 7.0, "name" : "wangwu", "age" : 43.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "GZ" } }
{ "_id" : 8.0, "name" : "zhaoliu", "age" : 44.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "SZ" } }
{ "_id" : 9.0, "name" : "tianqi", "age" : 45.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "TY" } }
{ "_id" : 10.0, "name" : "aaa", "age" : 140.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "BJ" } }
查询条件_id <=4 **************************************
{ "_id" : 1.0, "name" : "aaa", "age" : 180.0 }
{ "_id" : 2.0, "name" : "李四", "age" : 60.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "BJ" } }
{ "_id" : 3.0, "name" : "wangwu", "age" : 43.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "GZ" } }
{ "_id" : 4.0, "name" : "zhaoliu", "age" : 44.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "SZ" } }
查询条件_id <=4&&age>60 **************************************
{ "_id" : 1.0, "name" : "aaa", "age" : 180.0 }
查询条件_id <=4||age>60 **************************************
{ "_id" : 1.0, "name" : "aaa", "age" : 180.0 }
{ "_id" : 2.0, "name" : "李四", "age" : 60.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "BJ" } }
{ "_id" : 3.0, "name" : "wangwu", "age" : 43.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "GZ" } }
{ "_id" : 4.0, "name" : "zhaoliu", "age" : 44.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "SZ" } }
{ "_id" : 10.0, "name" : "aaa", "age" : 140.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "BJ" } }
{ "_id" : { "$oid" : "5c00e7520af8c80c1ed52c77" }, "name" : "aaa", "age" : 140.0 }
查询条件_id in 1,3,5 **************************************
{ "_id" : 1.0, "name" : "aaa", "age" : 180.0 }
{ "_id" : 3.0, "name" : "wangwu", "age" : 43.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "GZ" } }
{ "_id" : 5.0, "name" : "tianqi", "age" : 45.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "TY" } }
查询条件sort 按年龄排序(升序) **************************************
{ "_id" : 6.0, "name" : "lisi", "age" : 42.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "SH" } }
{ "_id" : 3.0, "name" : "wangwu", "age" : 43.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "GZ" } }
{ "_id" : 7.0, "name" : "wangwu", "age" : 43.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "GZ" } }
{ "_id" : 4.0, "name" : "zhaoliu", "age" : 44.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "SZ" } }
{ "_id" : 8.0, "name" : "zhaoliu", "age" : 44.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "SZ" } }
{ "_id" : 5.0, "name" : "tianqi", "age" : 45.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "TY" } }
{ "_id" : 9.0, "name" : "tianqi", "age" : 45.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "TY" } }
{ "_id" : 2.0, "name" : "李四", "age" : 60.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "BJ" } }
{ "_id" : 10.0, "name" : "aaa", "age" : 140.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "BJ" } }
{ "_id" : { "$oid" : "5c00e7520af8c80c1ed52c77" }, "name" : "aaa", "age" : 140.0 }
{ "_id" : 1.0, "name" : "aaa", "age" : 180.0 }
查询条件 分页 第二页 每页三条 **************************************
{ "_id" : 4.0, "name" : "zhaoliu", "age" : 44.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "SZ" } }
{ "_id" : 5.0, "name" : "tianqi", "age" : 45.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "TY" } }
{ "_id" : 10.0, "name" : "aaa", "age" : 140.0, "hobbies" : ["music", "read"], "addr" : { "country" : "China", "city" : "BJ" } }
查询条件 投影查询 **************************************
{ "name" : "wangwu", "age" : 43.0 }
条件查询3:聚合查询$match和$group和$project
@Test
public void testCrud06() {
/**
* 条件查询3
*/
//连接数据库,存在选中,不存在就建立
MongoDatabase database = mongoClient.getDatabase("javadb");
//获取集合
MongoCollection<Document> collection = database.getCollection("emp");
/**
* 使用$match和$group
* select * from db1.emp where post='公务员';
* db.emp.aggregate([{"$match":{"post":"公务员"}}])
*/
System.out.println("select * from db1.emp where post='公务员'*********************");
Document match = new Document("post","公务员");
Document doc1 = new Document("$match",match);
List<Document> list = new ArrayList<>();
list.add(doc1);
AggregateIterable<Document> iterable01 = collection.aggregate(list);
for (Document doc :iterable01){
System.out.println(doc.toJson());
}
/**
* select * from db1.emp where id > 3 group by post;
* db.emp.aggregate([
* {"$match":{"_id":{"$gt":3}}},
* {"$group":{"_id":"$post",'avg_salary':{"$avg":"$salary"}}}
* ])
*/
System.out.println("select * from db1.emp where id > 3 group by post*******************");
Document document2 = new Document();
document2.put("_id","$post");
document2.put("avg_salary",new Document("$avg","$salary"));
AggregateIterable<Document> iterable02 = collection.aggregate(
new ArrayList<Document>(Arrays.asList(
new Document("$match",new Document("_id",new Document("$gt",3))),
new Document("$group",document2)
))
);
for (Document doc :iterable02){
System.out.println(doc.toJson());
}
/**
* select post,max(salary) from db1.emp group by post;
* db.emp.aggregate([{"$group":{"_id":"$post","max_salary":{"$max":"$salary"}}}])
*/
System.out.println("select post,max(salary) from db1.emp group by post****************");
Document document3 = new Document();
document3.put("_id","$post");
document3.put("max_salary",new Document("$max","$salary"));
AggregateIterable<Document> iterable03 = collection.aggregate(
new ArrayList<Document>(Arrays.asList(
new Document("$group",document3)
))
);
for (Document doc :iterable03){
System.out.println(doc.toJson());
}
System.out.println("# select name,post,(age+1) as new_age from db1.emp;******************");
Document document4 = new Document();
document4.put("name",1);
document4.put("post",1);
document4.put("new_age",new Document("$add",new ArrayList<>(Arrays.asList("$age",1))));
AggregateIterable<Document> iterable04 = collection.aggregate(
new ArrayList<Document>(Arrays.asList(
new Document("$project",document4)
))
);
for (Document doc :iterable04){
System.out.println(doc.toJson());
}
}
结果:
select * from db1.emp where post='公务员'*********************
{ "_id" : 2.0, "name" : "武松", "sex" : "male", "age" : 78.0, "hire_date" : "20150302", "post" : "公务员", "salary" : 7.100000031E7 }
{ "_id" : 3.0, "name" : "宋江", "sex" : "male", "age" : 81.0, "hire_date" : "20130305", "post" : "公务员", "salary" : 78300.0 }
{ "_id" : 4.0, "name" : "林冲", "sex" : "male", "age" : 73.0, "hire_date" : "20140701", "post" : "公务员", "salary" : 73500.0 }
{ "_id" : 5.0, "name" : "林冲", "sex" : "male", "age" : 73.0, "hire_date" : "20140701", "post" : "公务员", "salary" : 73500.0 }
{ "_id" : 6.0, "name" : "柴进", "sex" : "male", "age" : 28.0, "hire_date" : "20121101", "post" : "公务员", "salary" : 72100.0 }
{ "_id" : 7.0, "name" : "卢俊义", "sex" : "female", "age" : 18.0, "hire_date" : "20110211", "post" : "公务员", "salary" : 79000.0 }
{ "_id" : 8.0, "name" : "高俅", "sex" : "male", "age" : 18.0, "hire_date" : "19000301", "post" : "公务员", "salary" : 730000.0 }
{ "_id" : 9.0, "name" : "鲁智深", "sex" : "male", "age" : 48.0, "hire_date" : "20101111", "post" : "公务员", "salary" : 710000.0 }
select * from db1.emp where id > 3 group by post*******************
{ "_id" : "文人", "avg_salary" : 716800.026 }
{ "_id" : "打手", "avg_salary" : 72600.294 }
{ "_id" : "公务员", "avg_salary" : 289683.3333333333 }
select post,max(salary) from db1.emp group by post****************
{ "_id" : "文人", "max_salary" : 720000.0 }
{ "_id" : "打手", "max_salary" : 74000.33 }
{ "_id" : "公务员", "max_salary" : 7.100000031E7 }
{ "_id" : "烧饼检察官", "max_salary" : 7300.33 }
# select name,post,(age+1) as new_age from db1.emp;******************
{ "_id" : 1.0, "name" : "武大郎", "post" : "烧饼检察官", "new_age" : 19.0 }
{ "_id" : 2.0, "name" : "武松", "post" : "公务员", "new_age" : 79.0 }
{ "_id" : 3.0, "name" : "宋江", "post" : "公务员", "new_age" : 82.0 }
{ "_id" : 4.0, "name" : "林冲", "post" : "公务员", "new_age" : 74.0 }
{ "_id" : 5.0, "name" : "林冲", "post" : "公务员", "new_age" : 74.0 }
{ "_id" : 6.0, "name" : "柴进", "post" : "公务员", "new_age" : 29.0 }
{ "_id" : 7.0, "name" : "卢俊义", "post" : "公务员", "new_age" : 19.0 }
{ "_id" : 8.0, "name" : "高俅", "post" : "公务员", "new_age" : 19.0 }
{ "_id" : 9.0, "name" : "鲁智深", "post" : "公务员", "new_age" : 49.0 }
{ "_id" : 10.0, "name" : "史进", "post" : "打手", "new_age" : 49.0 }
{ "_id" : 11.0, "name" : "李逵", "post" : "打手", "new_age" : 39.0 }
{ "_id" : 12.0, "name" : "周通", "post" : "打手", "new_age" : 19.0 }
{ "_id" : 13.0, "name" : "石秀", "post" : "打手", "new_age" : 19.0 }
{ "_id" : 14.0, "name" : "李忠", "post" : "打手", "new_age" : 29.0 }
{ "_id" : 15.0, "name" : "吴用", "post" : "文人", "new_age" : 29.0 }
{ "_id" : 16.0, "name" : "萧让", "post" : "文人", "new_age" : 19.0 }
{ "_id" : 17.0, "name" : "安道全", "post" : "文人", "new_age" : 19.0 }
{ "_id" : 18.0, "name" : "公孙胜", "post" : "文人", "new_age" : 19.0 }
{ "_id" : 19.0, "name" : "朱贵", "post" : "文人", "new_age" : 19.0 }
条件查询4:$sort和$limit和$skip
@Test
public void testCrud04() {
//连接数据库,存在选中,不存在就建立
MongoDatabase database = mongoClient.getDatabase("javadb");
//获取集合
MongoCollection<Document> collection = database.getCollection("emp");
/**
* 条件查询4
*/
System.out.println("取平均工资最高的第二个部门***************************");
Document group = new Document();
group.put("_id","$post");
group.put("平均工资",new Document("$avg","$salary"));
AggregateIterable<Document> iterable05 = collection.aggregate(
new ArrayList<Document>(Arrays.asList(
new Document("$group",group),
new Document("$sort",new Document("平均工资",-1)),
new Document("$limit",2),
new Document("$skip",1)
))
);
for (Document doc :iterable05){
System.out.println(doc.toJson());
}
}
取平均工资最高的第二个部门***************************
{ "_id" : "文人", "平均工资" : 716800.026 }