添加文档:
添加单个文档,多个文档
package com.bjsxt.mongodbdemo;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class InsertDocument {
MongoCollection collection = MongoDBPoolAuthUtil.getCollection("develop", "devtest");
public static void main(String[] args) {
InsertDocument insert=new InsertDocument();
//insert.insertSingleDocument();
insert.insertManyDocument();
}
/**
* 添加单个文档
*/
public void insertSingleDocument(){
Document document=new Document();
document.append("uname","lisi").append("age",25).append("userdesc","good").append("hobby", Arrays.asList(new String[]{"Music","Movie"}));
collection.insertOne(document);
}
/**
* 添加多个文档
*/
public void insertManyDocument(){
List<Document> documentList=new ArrayList<>();
for (int i=1;i<5;i++){
Document document=new Document();
document.append("uname","zs"+i);
document.append("age",25+i);
document.append("userdesc","prefect");
document.append("hobby", Arrays.asList(new String[]{"美女","Ballgame"}));
documentList.add(document);
}
collection.insertMany(documentList);
}
}
更新文档:
更新单个文档单个键,更新单个文档多个键,更新多个文档单个键,更新多个文档多个键,更新数组
package com.bjsxt.mongodbdemo;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import org.bson.Document;
public class UpdateDocument {
MongoCollection collection = MongoDBPoolAuthUtil.getCollection("develop", "devtest");
public static void main(String[] args) {
UpdateDocument update=new UpdateDocument();
//update.updateManyKeyDocument();
//update.updateManyDocumentSingleKey();
//update.updateManyDocumentManyKey();
// update.updateSingleDocumentArray();
update.updateManyDocumentArray();
}
/**
* 更新单个文档单个键
*/
public void updateSingleKeyDocument(){
collection.updateOne(Filters.eq("uname","lisi"),new Document("$set",new Document("age",28)));
}
/**
* 更新单个文档多个键
*/
public void updateManyKeyDocument(){
collection.updateOne(Filters.eq("uname","zs1"),new Document("$set",new Document("age",18).append("userdesc","very good")));
}
/**
* 更新多个文档单个键
*/
public void updateManyDocumentSingleKey(){
collection.updateMany(Filters.ne("uname",null),new Document("$set",new Document("userdesc","pretry good")));
}
/**
* 更新多个文档多个键
*/
public void updateManyDocumentManyKey(){
collection.updateMany(Filters.ne("uname",null),new Document("$set",new Document("userdesc","good").append("age",18)));
}
/**
* 更新单个文档的数组
*/
public void updateSingleDocumentArray(){
collection.updateMany(Filters.eq("uname","zs2"),new Document("$push",new Document("hobby","看小电影")));
}
/**
* 更新单个文档的多个数组
*/
public void updateManyDocumentArray(){
collection.updateMany(Filters.ne("uname",null),new Document("$push",new Document("hobby","欣赏小电影")));
}
}
查询文档:
查询全部文档,查询指定文档,查询多个文档(操作符)
package com.bjsxt.mongodbdemo;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.bson.types.ObjectId;
import java.util.regex.Pattern;
public class SelectDocument {
MongoCollection collection = MongoDBPoolAuthUtil.getCollection("develop", "devtest");
public static void main(String[] args) {
SelectDocument select=new SelectDocument();
//select.selectAll();
//select.selectById();
//select.selectManytype();
/*select.selectManyin();*/
//select.selectManynin();
//select.selectManyregex();
//select.selectManyand();
//select.selectManyor();
//select.selectManyorand();
select.selectManysort();
}
/**
* 查询所有
*/
public void selectAll(){
FindIterable<Document> iterable = collection.find();
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()){
Document doc = iterator.next();
System.out.println(doc.get("uname")+"\t"+doc.get("age")+"\t"+doc.get("userdesc")+"\t"+doc.get("hobby"));
}
}
/**
* 根据id查询
*/
public void selectById(){
FindIterable<Document> iterable = collection.find(Filters.eq("_id",new ObjectId("5dc0d6ca614f6b0a0c1915e3")));
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()){
Document doc = iterator.next();
System.out.println(doc.get("uname")+"\t"+doc.get("age")+"\t"+doc.get("userdesc")+"\t"+doc.get("hobby"));
}
}
/**
* 查询多个文档+gt
*/
public void selectManygt(){
FindIterable<Document> iterable = collection.find(Filters.gt("age",17));
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()){
Document doc = iterator.next();
System.out.println(doc.get("uname")+"\t"+doc.get("age")+"\t"+doc.get("userdesc")+"\t"+doc.get("hobby"));
}
}
/**
* 查询多个文档+type
*/
public void selectManytype(){
FindIterable<Document> iterable = collection.find(Filters.type("age","number"));
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()){
Document doc = iterator.next();
System.out.println(doc.get("uname")+"\t"+doc.get("age")+"\t"+doc.get("userdesc")+"\t"+doc.get("hobby"));
}
}
/**
* 查询多个文档+in
*/
public void selectManyin(){
FindIterable<Document> iterable = collection.find(Filters.in("uname","zs1","zs2","zs3"));
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()){
Document doc = iterator.next();
System.out.println(doc.get("uname")+"\t"+doc.get("age")+"\t"+doc.get("userdesc")+"\t"+doc.get("hobby"));
}
}
/**
* 查询多个文档+nin
*/
public void selectManynin(){
FindIterable<Document> iterable = collection.find(Filters.nin("uname","zs1","zs2","zs3"));
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()){
Document doc = iterator.next();
System.out.println(doc.get("uname")+"\t"+doc.get("age")+"\t"+doc.get("userdesc")+"\t"+doc.get("hobby"));
}
}
/**
* 查询多个文档以z开头2结尾
*/
public void selectManyregex(){
FindIterable<Document> iterable = collection.find(Filters.regex("uname", Pattern.compile("^z.*2$")));
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()){
Document doc = iterator.next();
System.out.println(doc.get("uname")+"\t"+doc.get("age")+"\t"+doc.get("userdesc")+"\t"+doc.get("hobby"));
}
}
/**
* 查询多个文档姓名是zs1,年龄是18
*/
public void selectManyand(){
FindIterable<Document> iterable = collection.find(Filters.and(Filters.eq("uname","zs1"),Filters.eq("age",18)));
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()){
Document doc = iterator.next();
System.out.println(doc.get("uname")+"\t"+doc.get("age")+"\t"+doc.get("userdesc")+"\t"+doc.get("hobby"));
}
}
/**
* 查询用户要求 uname 是 zs1,或者 age 是 18
*/
public void selectManyor(){
FindIterable<Document> iterable = collection.find(Filters.or(Filters.eq("uname","zs1"),Filters.eq("age",18)));
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()){
Document doc = iterator.next();
System.out.println(doc.get("uname")+"\t"+doc.get("age")+"\t"+doc.get("userdesc")+"\t"+doc.get("hobby"));
}
}
/**
* 查询文档中 uname 为 lisi 并且年龄为 18 岁,或者 userdesc 为 good
*/
public void selectManyorand(){
FindIterable<Document> iterable = collection.find(Filters.or(Filters.and(Filters.eq("uname","lisi"),Filters.eq("age",18)),Filters.eq("userdesc","good")));
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()){
Document doc = iterator.next();
System.out.println(doc.get("uname")+"\t"+doc.get("age")+"\t"+doc.get("userdesc")+"\t"+doc.get("hobby"));
}
}
/**
* 查询文档中 username 是 z 开头的,根据 username 对结果做降序排序。1升序排序, -1 降序排序规则 $sort:{username,-1}
*/
public void selectManysort(){
FindIterable<Document> iterable = collection.find(Filters.regex("uname",Pattern.compile("^z"))).sort(new Document("uname",-1));
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()){
Document doc = iterator.next();
System.out.println(doc.get("uname")+"\t"+doc.get("age")+"\t"+doc.get("userdesc")+"\t"+doc.get("hobby"));
}
}
}
对于时间的操作
插入主机时间,插入指定时间,根据指定日期去查询数据(操作符:gt,eq,)
package com.bjsxt.mongodbdemo;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import java.util.Date;
public class DateOperation {
MongoCollection collection = MongoDBPoolAuthUtil.getCollection("develop", "devtest");
public static void main(String[] args) {
DateOperation operation=new DateOperation();
//operation.insertDate();
//operation.insertCusDate();
//operation.SelectDate();
operation.SelectDategt();
}
/**
* 插入时间
*/
public void insertDate(){
Document doc=new Document();
doc.put("uname","ww");
doc.put("age",25);
doc.put("userdesc","very good");
doc.put("birth",new Date());
collection.insertOne(doc);
}
/**
* 插入指定日期
*/
public void insertCusDate(){
Date date=DateUtil.stringToDate("yyyy-MM-dd HH:mm:ss","2019-05-01 13:32:13");
Document doc=new Document();
doc.put("uname","zl");
doc.put("age",28);
doc.put("userdesc","very very good");
doc.put("birth",date);
collection.insertOne(doc);
}
/**
* 根据指定日期去查询数据
*/
public void SelectDate(){
Date date=DateUtil.stringToDate("yyyy-MM-dd hh:mm:ss","2019-05-01 13:32:13");
FindIterable iterable = collection.find(Filters.eq("birth", date));
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()){
Document doc = iterator.next();
String birth = DateUtil.dateToString("yyyy-MM-dd hh:mm:ss", (Date) doc.get("birth"));
System.out.println(doc.get("uname")+"\t"+doc.get("age")+"\t"+doc.get("userdesc")+"\t"+birth);
}
}
/**
* 根据指定日期去查询数据
*/
public void SelectDategt(){
Date date=DateUtil.stringToDate("yyyy-MM-dd hh:mm:ss","2019-01-01 00:00:00");
FindIterable iterable = collection.find(Filters.gt("birth", date));
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()){
Document doc = iterator.next();
String birth = DateUtil.dateToString("yyyy-MM-dd hh:mm:ss", (Date) doc.get("birth"));
System.out.println(doc.get("uname")+"\t"+doc.get("age")+"\t"+doc.get("userdesc")+"\t"+birth);
}
}
}
聚合操作(各种查询,操作符)
package com.bjsxt.mongodbdemo;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AggregateOperation {
MongoCollection collection = MongoDBPoolAuthUtil.getCollection("develop", "devtest");
public static void main(String[] args) {
AggregateOperation operation = new AggregateOperation();
//operation.selectDocumentAggregateCount();
//operation.selectDocumentAggregateSum();
//operation.selectDocumentAggregateGroupBySum();
//operation.selectDocumentAggregateGroupByWhere();
//operation.selectDocumentAggregateGroupByHaving();
//operation.selectDocumentProject();
//operation.selectDocumentProjectConcat();
//operation.selectDocumentProjectAdd();
operation.selectDocumentProjectDate();
}
/**
* 查询集合中的文档数量
* MongoShell:db.dev.aggregate([{$group:{_id:null,count:{$sum:1}}
*/
public void selectDocumentAggregateCount() {
Document doc = new Document();
doc.put("$sum", 1);
Document count = new Document();
count.put("_id", null);
count.put("count", doc);
Document group = new Document();
group.put("$group", count);
List<Document> list = new ArrayList<>();
list.add(group);
AggregateIterable iterable = collection.aggregate(list);
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()) {
Document docu = iterator.next();
System.out.println(docu.get("count"));
}
}
/**
* 需求:查询集合中所有 age 键中的值的总和
* MongoShell:db.dev.aggregate([{$group:{_id:null,totalSize:{$sum:"$size"}}}])
*/
public void selectDocumentAggregateSum() {
Document document = new Document();
document.put("$sum", "$age");
Document sumage = new Document();
sumage.put("_id", null);
sumage.put("sumage", document);
Document group = new Document();
group.put("$group", sumage);
List<Document> list = new ArrayList<>();
list.add(group);
AggregateIterable iterable = collection.aggregate(list);
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()) {
Document doc = iterator.next();
System.out.println("sum_age: " + doc.get("sumage"));
}
}
/**
* 需求:对 uname 进行分组,计算每组中的 age 的总和
* MongoShell:db.dev.aggregate([{$group:{_id:"$title",totalSize:{$sum:"$size"}}}])
*/
public void selectDocumentAggregateGroupBySum() {
Document document = new Document();
document.put("$sum", "$age");
Document sumage = new Document();
sumage.put("_id", "$uname");
sumage.put("sumage", document);
Document group = new Document();
group.put("$group", sumage);
List<Document> list = new ArrayList<>();
list.add(group);
AggregateIterable iterable = collection.aggregate(list);
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()) {
Document doc = iterator.next();
System.out.println(doc.get("_id") + "\t" + doc.get("sumage"));
}
}
/**
* 需求:查询 devtest 集合有多少文档的 age 大于 20。
* Mongo Shell:db.dev.aggregate([{$match:{size:{$gt:200}}},{$group:{_id:null,totalSize:{$sum:1}}}])
*/
public void selectDocumentAggregateGroupByWhere() {
Document match = new Document();
match.put("$match", new Document("age", new Document("$gt", 20)));
Document sumage = new Document();
sumage.put("$sum", 1);
Document two = new Document();
two.put("_id", null);
two.put("sumage", sumage);
Document group = new Document();
group.put("$group", two);
List<Document> list = new ArrayList<>();
list.add(match);
list.add(group);
AggregateIterable iterable = collection.aggregate(list);
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()) {
Document doc = iterator.next();
System.out.println(doc.get("sumage"));
}
}
/**
* 需求:查询 devtest 集合,根据 uname 分组计算出每组的 age 的总和,并过滤掉总和小于 20 的文档。
* Mongo Shell:db.dev.aggregate([{$group:{_id:"$title",totalSize:{$sum:"$size"}}},{$match:{totalSize:{$gt:200}}}])
*/
public void selectDocumentAggregateGroupByHaving() {
Document match = new Document();
match.put("$match", new Document("sumage", new Document("$gt", 20)));
Document sumage = new Document();
sumage.put("$sum", "$age");
Document two = new Document();
two.put("_id", "$uname");
two.put("sumage", sumage);
Document group = new Document();
group.put("$group", two);
List<Document> list = new ArrayList<>();
list.add(group);
list.add(match);
AggregateIterable iterable = collection.aggregate(list);
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()) {
Document doc = iterator.next();
System.out.println(doc.get("_id")+"\t"+doc.get("sumage"));
}
}
/**
* 需求:查询 devtest 集合,将数组中的内容拆分显示,并只显示 uname 键与 hobby键的值。
* Mongo Shell:db.dev.aggregate([{$unwind:"$tags"},{$project:{_id:0,tags:"$tags",title:"$title"}}])
*/
public void selectDocumentProject(){
Document unwind=new Document();
unwind.put("$unwind","$hobby");
Document show=new Document();
show.put("_id",0);
show.put("hobby","$hobby");
show.put("uname","$uname");
Document project=new Document();
project.put("$project",show);
List<Document> list=new ArrayList<>();
list.add(unwind);
list.add(project);
AggregateIterable iterable = collection.aggregate(list);
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()) {
Document doc = iterator.next();
System.out.println(doc);
}
}
/**
* 需求:查询 devtest 集合,将数组中的内容拆分显示。将 uname 字段和 hobby字段的值拼接为一个完整字符串并在 uname_hooby 字段中显示。
* Mongo Shell:db.dev.aggregate([{$unwind:"$tags"},{$project:{_id:0,Title_Tags:{$concat:["$title","-","$tags"]}}}])
*/
public void selectDocumentProjectConcat(){
Document unwind=new Document();
unwind.put("$unwind","$hobby");
Document concat=new Document();
concat.put("$concat", Arrays.asList(new String[]{"$uname","_","$hobby"}));
Document nh=new Document();
nh.put("_id",0);
nh.put("uname_hooby",concat);
Document project=new Document();
project.put("$project",nh);
List<Document> list=new ArrayList<>();
list.add(unwind);
list.add(project);
AggregateIterable iterable = collection.aggregate(list);
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()) {
Document doc = iterator.next();
System.out.println(doc);
}
}
/**
* 需求:查询 devtest 集合中数据,显示 uname 和 age 字段,为 age 字段数据做加 1 操作,显示字段命名为 age。排除那些没有 age 键的文档。
* Mongo Shell:db.dev.aggregate([{$match:{size:{$ne:null}}},{$project:{_id:0,title:1,New_Size:{$add:["$size",1]}}}])
*/
public void selectDocumentProjectAdd(){
Document ne =new Document();
ne.put("$ne",null);
Document age=new Document();
age.put("age",ne);
Document match=new Document();
match.put("$match",age);
Document add=new Document();
add.put("$add",Arrays.asList(new Object[]{"$age",1}));
Document show =new Document();
show.put("_id",0);
show.put("uname",1);
show.put("age",add);
Document project =new Document();
project.put("$project",show);
List<Document> list=new ArrayList<>();
list.add(match);
list.add(project);
AggregateIterable iterable = collection.aggregate(list);
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()) {
Document doc = iterator.next();
System.out.println(doc);
}
}
/**
* 需求:查询 devtest 集合查询那些有生日的用户,并按照 YYYY 年 mm 月dd 日 HH:MM:SS 格式显示日期。
* 注意:如果直接在 MongoDB 中做日期的格式化处理,那么是按照表示 UTC时间来处理的,会少 8 个小时。建议在程序中
* 通过 java.util.Date 来做日期的转换。
* Mongo Shell:db.devtest.aggregate([{$match:{userbirth:{$ne:null}}},{$project:{自定义日期格式:{$dateToString:{format:"%Y 年%m 月%d日 %H:%M:%S",date:"$userbirth"}}}}])
*/
public void selectDocumentProjectDate(){
Document ne =new Document();
ne.put("$ne",null);
Document birth=new Document();
birth.put("birth",ne);
Document match=new Document();
match.put("$match",birth);
//{$project:{自定义日期格式:{$dateToString:{format:"%Y 年%m 月%d日 %H:%M:%S",date:"$userbirth"}}}}
Document format=new Document();
format.put("format","%Y 年%m 月%d日 %H:%M:%S");
format.put("date","$birth");
Document dateToString=new Document();
dateToString.put("$dateToString",format);
Document zdy=new Document();
zdy.put("自定义日期格式",dateToString);
Document project=new Document();
project.put("$project",zdy);
List<Document> list=new ArrayList<>();
list.add(match);
list.add(project);
AggregateIterable iterable = collection.aggregate(list);
MongoCursor<Document> iterator = iterable.iterator();
while (iterator.hasNext()) {
Document doc = iterator.next();
System.out.println(doc);
}
}
}
日期的转化工具类
package com.bjsxt.mongodbdemo;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
/**
* date to string
*/
public static String dateToString(String pattern, Date date){
SimpleDateFormat spdf=new SimpleDateFormat(pattern);
String format = spdf.format(date);
return format;
}
/**
* String to date
*/
public static Date stringToDate(String pattern, String date){
SimpleDateFormat spdf=new SimpleDateFormat(pattern);
try {
Date parse = spdf.parse(date);
return parse;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
俩种分页操作
package com.bjsxt.mongodbdemo;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
import org.bson.types.ObjectId;
public class SelectDocumentByPage {
MongoCollection collection = MongoDBPoolAuthUtil.getCollection("develop", "devtest");
public static void main(String[] args) {
SelectDocumentByPage docd=new SelectDocumentByPage();
//docd.selectDocumentByPageUseSkipAndLimit(3);
docd.selectDocumentByPageUseCondition(2,2,"5dc0d85c614f6b2730c1d0fd");
}
/**
* 实现分页查询
*/
public void selectDocumentByPageUseSkipAndLimit(int pageIndex){
int page=(pageIndex-1)*2;
Document doc=new Document("age",new Document("$ne",null));
long count = collection.countDocuments(doc);
System.out.println(count);
FindIterable ite = collection.find(doc).limit(2).skip(page);
MongoCursor<Document> iterator = ite.iterator();
while (iterator.hasNext()){
Document docu = iterator.next();
System.out.println(docu);
}
}
/**
* 条件判断实现分页
*/
public void selectDocumentByPageUseCondition(int pageIndex,int pageSize,String lastId){
Document doc=new Document("age",new Document("$ne",null));
long count = collection.countDocuments(doc);
System.out.println(count);
FindIterable ite =null;
if (pageIndex==1){
ite = collection.find(doc).limit(pageSize);
}else {
if (lastId!=null){
doc.append("_id",new Document("$gt",new ObjectId(lastId)));
ite = collection.find(doc).limit(pageSize);
}
}
MongoCursor<Document> iterator = ite.iterator();
while (iterator.hasNext()){
Document docu = iterator.next();
System.out.println(docu);
}
}
}