Loading

mongo-java-driver操作MongoDB

引入依赖:

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.8.2</version>
</dependency>


1、连接MongoDB数据库

1)直连方式

public class MongoDBUtil {

    private static MongoClient client = null;

    static {
        if(client==null){
            client = new MongoClient("192.168.3.56", 27017);
        }
    }

    //获取MongoDB数据库
    public static MongoDatabase getDatabase(String databaseName){
        return client.getDatabase(databaseName);
    }

    //获取Mongo集合
    public static MongoCollection getCollection(String databaseName,String collectionName){
        return getDatabase(databaseName).getCollection(collectionName);
    }
}


2)直连方式支持用户认证

/**
 * @author houChen
 * @date 2021/7/10 17:34
 * @Description: 创建MongoDB拦截,使用用户认证
 */
public class MongoDBAuthUtil {

    private static MongoClient client = null;

    static {
        if(client==null){
            //创建一个用户认证信息
            MongoCredential credential = MongoCredential.createCredential("itsxt","develope","itsxtpwd".toCharArray());
            //封装MongoDB的地址和端口
            ServerAddress address = new ServerAddress("192.168.3.56", 27017);
            //方法过时是由于现在推荐池连的方式
            client = new MongoClient(address, Arrays.asList(credential));
        }
    }

    //获取MongoDB数据库
    public static MongoDatabase getDatabase(String databaseName){
        return client.getDatabase(databaseName);
    }

    //获取Mongo集合
    public static MongoCollection getCollection(String databaseName,String collectionName){
        return getDatabase(databaseName).getCollection(collectionName);
    }
}


3)池连方式

public class MongoDBPoolUtil {

    private static MongoClient client = null;

    static {
        if(client==null){
            MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
            //设置每个连接地址的最大连接数
            builder.connectionsPerHost(10);
            //设置连接的超时时间
            builder.connectTimeout(5000);
            //设置读写的超时时间
            builder.socketTimeout(5000);
            ServerAddress address = new ServerAddress("192.168.3.56", 27017);
            client = new MongoClient(address,builder.build());
        }
    }

    //获取MongoDB数据库
    public static MongoDatabase getDatabase(String databaseName){
        return client.getDatabase(databaseName);
    }

    //获取Mongo集合
    public static MongoCollection getCollection(String databaseName, String collectionName){
        return getDatabase(databaseName).getCollection(collectionName);
    }
}


4)池连方式支持认证

/**
 * @author houChen
 * @date 2021/7/10 18:08
 * @Description:  支持用户认证的池连
 */
public class MongoDBPoolAuthUtil {

    private static MongoClient client = null;

    static {
        if(client==null){
            MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
            //设置每个连接地址的最大连接数
            builder.connectionsPerHost(10);
            //设置连接的超时时间
            builder.connectTimeout(5000);
            //设置读写的超时时间
            builder.socketTimeout(5000);
            //创建一个用户认证信息
            MongoCredential credential = MongoCredential.createCredential("itsxt","develope","itsxtpwd".toCharArray());
            //封装MongoDB的地址和端口
            ServerAddress address = new ServerAddress("192.168.3.56", 27017);
            client = new MongoClient(address,credential,builder.build());
        }
    }

    //获取MongoDB数据库
    public static MongoDatabase getDatabase(String databaseName){
        return client.getDatabase(databaseName);
    }

    //获取Mongo集合
    public static MongoCollection getCollection(String databaseName, String collectionName){
        return getDatabase(databaseName).getCollection(collectionName);
    }
}


2、操作集合

1)创建集合

MongoDatabase develope = MongoDBPoolUtil.getDatabase("develope");
develope.createCollection("test1");


2)获取集合

MongoCollection<Document> test = develope.getCollection("test");
System.out.println(test.getNamespace());


3)删除集合

MongoCollection<Document> test = develope.getCollection("test1");
test.drop();


3、插入文档

1)单个文档插入

public void insertSingleDocument(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");
    Document document = new Document();
    document.append("username","liss").append("age",18 ).append("desc", "prefect");
    collection.insertOne(document);
}


2)插入多个文档

public void insertManyDocument(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");
    List<Document> list = new ArrayList<Document>();
    for(int i=0;i<5;i++){
        Document document = new Document();
        document.append("username","liss"+i).append("age",18+i ).append("desc", "prefect"+i);
        list.add(document);
    }
    collection.insertMany(list);
}


4、更新文档

1)更新单个文档单个键

/*
更新单个文档单个key
 */
public void updateSingleDocumentSingleKey(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");

    collection.updateOne(Filters.eq("username","liss"),
            new Document("$set",new Document("userage",100)));
}


2)更新单个文档多个键

/*
更新单个文档多个键
 */
public void updateSingleDocumentManyKey(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");

    collection.updateOne(Filters.eq("username","liss"),
            new Document("$set",new Document("userage",100).append("age", "13")));
}


3)更新多个文档单个键

/*
更新单个文档单个个键
将username不为空的文档的age修改为100
 */
public void updateManyDocumentSingleKey(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");

    collection.updateMany(Filters.ne("username",null),
            new Document("$set",new Document("desc","very good")));
}

clipboard


4)更新多个文档的多个键

/*
更新多个文档多个键
将username不为空的文档的age修改为3岁,desc修改为哈哈哈哈
 */
 public void updateManyDocumentManyKey(){
     MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");

     collection.updateMany(Filters.ne("username",null),
             new Document("$set",new Document("age","3岁").append("desc", "哈哈哈哈")));
 }

clipboard


5)更新文档的数组

/*
    更新文档的数组
    将username为lisi的insterts数组中添加art
 */
public void updateArray(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");
    collection.updateOne(Filters.eq("username", "liss"),
            new Document("$push",new Document("insterts","art")));
}

clipboard


5、查询文档

1)查询所有文档

public void searchAllDocument(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");
    FindIterable<Document> iterable = collection.find(); //返回的是一个迭代器
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("username")+" "+document.get("age"));
    }
}


2)根据_id查询文档

/*
根据_id查询文档
 */
public void searchDocumentById(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");
    FindIterable<Document> iterable = collection.find(Filters.eq("_id",new ObjectId("60ea475b28339539c8b814f4"))); //返回的是一个迭代器
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("username")+" "+document.get("age"));
    }
}


3)查询多个文档 $gt

/*
    查询多个文档 $gt
    查询年龄大于19的文档
 */
public void searchDocumentByCondition(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");
    FindIterable<Document> iterable = collection.find(Filters.gt("age",19)); //返回的是一个迭代器
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("username")+" "+document.get("age"));
    }
}


4)查询多个文档 $type

/*
    查询多个文档 $type
    查询age为number文档
 */
public void searchDocumentByType(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");
    FindIterable<Document> iterable = collection.find(Filters.type("age","number")); //返回的是一个迭代器
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("username")+" "+document.get("age"));
    }
}


5)查询多个文档 $in $nin

/*
    查询多个文档 $in
    查询username为liss,liss1,liss2文档
    $nin=>表示不在这个数组中的文档 ·
 */
public void searchDocumentByIn(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");
    FindIterable<Document> iterable = collection.find(Filters.in("username","liss","liss1","liss2")); //返回的是一个迭代器
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("username")+" "+document.get("age"));
    }
}


6)查询多个文档 $regex (根据正则表达式来查询)

/*
    查询多个文档 $regex
    查询以l开头,2结尾的文档
 */
public void searchDocumentByRegex(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");
    FindIterable<Document> iterable = collection.find(Filters.regex("username","^l.*2$")); //返回的是一个迭代器
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("username")+" "+document.get("age"));
    }
}


7)查询多个文档 逻辑运算符 $and $or

/*
查询文档 逻辑运算符$and
查询用户名称为liss1 年龄为18的文档
 */
public void searchDocumentByAnd(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");
    FindIterable<Document> iterable = collection.find(Filters.and(Filters.eq("username","liss"),Filters.eq("age", 18))); //返回的是一个迭代器
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("username")+" "+document.get("age"));
    }
}

/*
查询文档 逻辑运算符$or
查询用户名称为liss1 或者年龄为18的文档
 */
public void searchDocumentByAnd(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");
    FindIterable<Document> iterable = collection.find(Filters.or(Filters.eq("username","liss"),Filters.eq("age", 18))); //返回的是一个迭代器
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("username")+" "+document.get("age"));
    }
}


8)查询文档 - 排序处理

/*
查询文档  $and和$or联合使用
查询文档,根据userName降序排序
 */
public void searchDocumentBySort(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");
    FindIterable<Document> iterable = collection.find().sort(new Document("username", 1));
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("username")+" "+document.get("age"));
    }
}


6、日期操作

1)插入系统当前日期

/*
插入系统当前日期
 */
public void insertSystemDate(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","date");
    Document document = new Document();
    document.put("username", "zhangsan");
    document.put("age", 22);
    document.put("desc", "very good");
    document.put("userBirth", new Date());
    collection.insertOne(document);
}

clipboard


2)添加指定日期

/*
插入指定日期
 */
 public void insertDate() throws ParseException {
     MongoCollection collection = MongoDBPoolUtil.getCollection("develope","date");

     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
     Date date = simpleDateFormat.parse("2021-07-16 08:00:00");

     Document document = new Document();
     document.put("username", "zhangsan");
     document.put("age", 22);
     document.put("desc", "very good");
     document.put("userBirth", date);
     collection.insertOne(document);
 }

clipboard


3)查询日期 $eq

/*
查询日期 $qe
 */
public void searchByDate() throws ParseException {
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","date");

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    Date date = simpleDateFormat.parse("2021-07-16 08:00:00");
    FindIterable<Document> iterable = collection.find(Filters.eq("userBirth",date)); //返回的是一个迭代器
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("username")+" "+ document.get("age")+" "+document.get("userBirth"));
    }
}

【注意】java会将mongo中查出来的时间自动转化时区


7、聚合操作

1)计算文档总数

查询test集合中文档的数量

clipboard

/*
$sum
查询集合中的文档数量
 */
public void selectDocumentAggregateCount(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test");
    Document sum = new Document();
    sum.put("$sum", 1);
    Document count = new Document();
    count.put("_id", null);
    count.put("count",sum);
    Document group = new Document();
    group.put("$group",count);
    List<Document> list = new ArrayList<Document>();
    list.add(group);
    AggregateIterable iterable = collection.aggregate(list);
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("_id")+" "+document.get("count"));
    }
}


2)聚合操作 $sum

以title进行分组,并计算每组size的总和

clipboard

public void selectDocumentAggregateSizeSum(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1");
    Document sum = new Document();
    sum.put("$sum", "$size");
    Document count = new Document();
    count.put("_id", "$title");
    count.put("count",sum);
    Document group = new Document();
    group.put("$group",count);
    List<Document> list = new ArrayList<Document>();
    list.add(group);
    AggregateIterable iterable = collection.aggregate(list);
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("_id")+" "+document.get("count"));
    }
}


3)聚合操作:分组前的数据过滤

查询dev集合size > 200 的文档,并按照title分组,计算size的总和

clipboard

/*
 聚合操作:分组前的数据过滤
 查询dev集合有多少size > 200 的文档
 */
public void selectDocumentAggregateSizeGt200(){
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test");
    Document size = new Document();
    size.put("size", new Document().append("$gt", 200));
    Document match = new Document();
    match.put("$match", size);

    Document sum = new Document();
    sum.put("$sum", "$size");
    Document count = new Document();
    count.put("_id", "$title");
    count.put("count",sum);
    Document group = new Document();
    group.put("$group",count);
    List<Document> list = new ArrayList<Document>();
    list.add(match);
    list.add(group);
    AggregateIterable iterable = collection.aggregate(list);
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("_id")+" "+document.get("count"));
    }
}


4)聚合操作 $project 聚合投影约束


5)分页操作 使用skip和limit进行分页

/*
分页操作 使用skip和limit进行分页
 */
public void selectDocumentByPage(int page) {
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope", "test");
    FindIterable iterable = collection.find().skip((page - 1) * 2).limit(2);
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("_id")+" "+document.get("title")+" "+document.get("size"));
    }
}


6)分页查询优化

使用条件判断替换skip方法

=》查询大于某个条件的所有文档,然后再进行分页

/*
分页操作 使用条件判断实现分页查询
 */
public void selectDocumentByPage1(int pageIndex,int page,String lastId) {
    MongoCollection collection = MongoDBPoolUtil.getCollection("develope", "test");
    FindIterable iterable = null;
    Document condition = new Document();
    if(pageIndex==1){
        iterable = collection.find(condition).limit(page);
    }else{
        if(lastId != null){
            condition.append("_id", new Document("$gt",new ObjectId(lastId));
            iterable = collection.find(condition).limit(page);
        }
    }
    MongoCursor<Document> cursor = iterable.iterator();  //返回的是一个游标
    while (cursor.hasNext()){
        Document document = cursor.next();
        System.out.println(document.get("_id")+" "+document.get("title")+" "+document.get("size"));
    }
}
posted @ 2021-07-14 07:39  青岑  阅读(1398)  评论(0编辑  收藏  举报