ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

java操作MongoDB

2020-03-28 22:03:24  阅读:215  来源: 互联网

标签:java MongoDB collection public 文档 Test 操作 查询 id


mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动。 我们通过一个入门的案例来了解mongodb-driver的基本使用

创建工程 mongoDemo, 引入依赖

<dependencies>
 <dependency>
 <groupId>org.mongodb</groupId> 
<artifactId>mongodb‐driver</artifactId>
 <version>3.6.3</version>
 </dependency> 
</dependencies>

创建测试类

import com.mongodb.*;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;

public class MogoDBTest {


    private static MongoClient mongoClient;

    static {
        System.out.println("===============MongoDBUtil初始化========================");
        mongoClient = new MongoClient("127.0.0.1", 27017);
        // 大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码:
        // boolean auth = db.authenticate(myUserName, myPassword);
        MongoClientOptions.Builder options = new MongoClientOptions.Builder();
        options.cursorFinalizerEnabled(true);
        // options.autoConnectRetry(true);// 自动重连true
        // options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time
        options.connectionsPerHost(300);// 连接池设置为300个连接,默认为100
        options.connectTimeout(30000);// 连接超时,推荐>3000毫秒
        options.maxWaitTime(5000); //
        options.socketTimeout(0);// 套接字超时时间,0无限制
        options.threadsAllowedToBlockForConnectionMultiplier(5000);// 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。
        options.writeConcern(WriteConcern.SAFE);//
        options.build();
    }

    // =================公用用方法=================
    /**
     * 获取DB实例 - 指定数据库,若不存在则创建
     * @param dbName
     * @return
     */
    public static MongoDatabase getDB(String dbName) {
        if (dbName != null && !"".equals(dbName)) {
            MongoDatabase database = mongoClient.getDatabase(dbName);
            return database;
        }
        return null;
    }

    /**
     * 获取指定数据库下的collection对象
     * @param collName
     * @return
     */
    public static  MongoCollection<Document> getCollection(String dbName, String collName) {
        if (null == collName || "".equals(collName)) {
            return null;
        }
        if (null == dbName || "".equals(dbName)) {
            return null;
        }
        MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName);
        return collection;
    }

..................... }

1.数据库操作

1.1获取所有数据库

  //获取所有数据库
    @Test
    public void getAllDBNames(){
        MongoIterable<String> dbNames = mongoClient.listDatabaseNames();
        for (String s : dbNames) {
            System.out.println(s);
        }
    }

1.2.获取指定库的所有集合名

    //获取指定库的所有集合名
    @Test
    public void getAllCollections(){
        MongoIterable<String> colls = getDB("books").listCollectionNames();
        for (String s : colls) {
            System.out.println(s);
        }
    }

1.3.删除数据库

  //删除数据库
    @Test
    public void dropDB(){
        //连接到数据库
        MongoDatabase mongoDatabase =  getDB("test");
        mongoDatabase.drop();
    }

2.文档操作  

2.1插入文档

1.插入单个文档

    //插入一个文档
    @Test
    public void insertOneTest(){
        //获取集合
        MongoCollection<Document> collection = getCollection("books","book");
        //要插入的数据
        Document document = new Document("id",1)
                .append("name", "哈姆雷特")
                .append("price", 67);
        //插入一个文档
        collection.insertOne(document);
        System.out.println(document.get("_id"));
    }

 2.插入多个文档

  //插入多个文档
    @Test
    public void insertManyTest(){
        //获取集合
        MongoCollection<Document> collection = getCollection("books","book");
        //要插入的数据
        List<Document> list = new ArrayList<>();
        for(int i = 1; i <= 15; i++) {
            Document document = new Document("id",i)
                    .append("name", "book"+i)
                    .append("price", 20+i);
            list.add(document);
        }
        //插入多个文档
        collection.insertMany(list);
    }

2.2查询文档

2.2.1基本查询

 1.查询集合所有文档

    @Test
    public void findAllTest(){
        //获取集合
        MongoCollection<Document> collection = getCollection("books","book");
        //查询集合的所有文档
        FindIterable findIterable= collection.find();
        MongoCursor cursor = findIterable.iterator();
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    }

2.条件查询

  @Test
    public void findConditionTest(){
        //获取集合
        MongoCollection<Document> collection = getCollection("books","book");
        //方法1.构建BasicDBObject  查询条件 id大于2,小于5 
        queryCondition.put("id", new BasicDBObject("$gt", 2));
        queryCondition.put("id", new BasicDBObject("$lt", 5));
        //查询集合的所有文  通过price升序排序
        FindIterable findIterable= collection.find(queryCondition).sort(new BasicDBObject("price",1));
//方法2.通过过滤器Filters,Filters提供了一系列查询条件的静态方法 id大于2小于5 通过id升序排序查询 //Bson filter=Filters.and(Filters.gt("id", 2),Filters.lt("id", 5)); //FindIterable findIterable= collection.find(filter).sort(Sorts.orderBy(Sorts.ascending("id")));
//查询集合的所有文 MongoCursor cursor = findIterable.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } }

  

2.2.2 投影查询

    @Test
    public void findAllTest3(){
        //获取集合
        MongoCollection<Document> collection = getCollection("books","book");
      //查询id等于1,2,3,4的文档
        Bson fileter=Filters.in("id",1,2,3,4);
        //查询集合的所有文档
        FindIterable findIterable= collection.find(fileter).projection(new BasicDBObject("id",1).append("name",1).append("_id",0));
        MongoCursor cursor = findIterable.iterator();
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    }

2.3分页查询 

2.3.1.统计查询

//集合的文档数统计
    @Test
    public void getCountTest() {
        //获取集合
        MongoCollection<Document> collection = getCollection("books","book");
        //获取集合的文档数
        Bson filter = Filters.gt("price", 30);
        int count = (int)collection.count(filter);
        System.out.println("价钱大于30的count==:"+count);
    }

  

2.3.2分页列表查询 

    //分页查询
    @Test
    public void findByPageTest(){
        //获取集合
        MongoCollection<Document> collection = getCollection("books","book");
        //分页查询  跳过0条,返回前10条
        FindIterable findIterable= collection.find().skip(0).limit(10);
        MongoCursor cursor = findIterable.iterator();
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
        System.out.println("----------取出查询到的第一个文档-----------------");
        //取出查询到的第一个文档
        Document document = (Document) findIterable.first();
        //打印输出
        System.out.println(document);
    }

2.4修改文档

  //修改文档
    @Test
    public void updateTest(){
        //获取集合
        MongoCollection<Document> collection = getCollection("books","book");
        //修改id=2的文档    通过过滤器Filters,Filters提供了一系列查询条件的静态方法
        Bson filter = Filters.eq("id", 2);
        //指定修改的更新文档
        Document document = new Document("$set", new Document("price", 44));
        //修改单个文档
        collection.updateOne(filter, document);
        //修改多个文档
      // collection.updateMany(filter, document);
        //修改全部文档
        //collection.updateMany(new BasicDBObject(),document);
    }

2.5 删除文档

  //删除与筛选器匹配的单个文档
    @Test
    public void deleteOneTest(){
        //获取集合
        MongoCollection<Document> collection = getCollection("books","book");
        //申明删除条件
        Bson filter = Filters.eq("id",3);
        //删除与筛选器匹配的单个文档
        collection.deleteOne(filter);

        //删除与筛选器匹配的所有文档
       // collection.deleteMany(filter);

        System.out.println("--------删除所有文档----------");
        //删除所有文档
       // collection.deleteMany(new Document());
    }

  

 

标签:java,MongoDB,collection,public,文档,Test,操作,查询,id
来源: https://www.cnblogs.com/mabaoying/p/12589583.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有