第四节 java driver操作MongoDB

亮子 2021-06-18 03:52:22 17729 0 0 0

1、添加依赖

  • 官方文档

https://mongodb.github.io/mongo-java-driver/4.0/driver/getting-started/installation/

  • 添加MongoDB驱动依赖
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-sync</artifactId>
            <version>4.0.6</version>
        </dependency>
  • 添加测试依赖
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

2、准备测试类

package com.shenmazong;


import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.shenmazong.pojo.TbHero;
import org.bson.Document;
import org.junit.Before;

public class MongoDatabaseTest {

    private MongoDatabase db_hero;
    private MongoCollection<Document> tb_hero;
    private MongoClient client;

    @Before
    public void init(){
        // 1、连接MongoDB服务器
        client = new MongoClient("127.0.0.1",27017);

        // 2、选择数据库
        db_hero =client.getDatabase("db_hero");

        // 3、选择集合
        tb_hero = db_hero.getCollection("tb_hero");
    }
}

3、添加文档

  • 添加一条数据
    @Test
    public void insertOne() {
        Document doc = new Document();
        doc.append("id", 1);
        doc.append("name", "武松");
        doc.append("age", 33);
        doc.append("work", "专业打老虎");

        tb_hero.insertOne(doc);
        System.out.println(doc);
    }
  • 添加多条数据
    @Test
    public void insertMany() {
        List<Document> collections = new ArrayList<Document>();
        Document doc1 = new Document();
        doc1.append("id", 2).append("name", "史进").append("age", 33).append("work", "九纹龙");
        collections.add(doc1);

        Document doc2 = new Document();
        doc2.append("id", 3).append("name", "宋江").append("age", 33).append("work", "及时雨");
        collections.add(doc2);

        tb_hero.insertMany(collections);
    }

4、修改文档

  • 修改符合条件的第一条数据
    @Test
    public void updateOne() {
        tb_hero.updateOne(
                Filters.eq("name", "武松"),
                new Document("$set", new Document("name", "武松1"))
        );
    }
  • 修改符合条件的所有记录
    @Test
    public void updateMany() {
        tb_hero.updateMany(
                Filters.eq("name", "武松"),
                new Document("$set", new Document("name", "武松666"))
        );
    }

5、查询文档

  • 查询所有文档
    @Test
    public void findAll() {
        FindIterable<Document> documents = tb_hero.find();
        MongoCursor<Document> iterator = documents.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
  • 条件查询
    @Test
    public void findQuery() {
        FindIterable<Document> documents = tb_hero.find(Filters.eq("name", "武松1"));
        MongoCursor<Document> iterator = documents.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
  • and条件查询
    @Test
    public void findQueryMulti() {
        BasicDBObject doc5 = new BasicDBObject();
        doc5.put("age", 43);
        doc5.put("name", "鲁智深");
        //doc5.put("url", "{$regex:'2016'}");错误的写法
//        BasicDBObject doc3 = new BasicDBObject();
//        doc3.put("$regex", "2016");
//        doc5.put("url", doc3);
        FindIterable<Document> documents = tb_hero.find(doc5);

        MongoCursor<Document> iterator = documents.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
    @Test
    public void findQueryMulti2() {
        Bson condition = Filters.and(Filters.eq("name", "鲁智深"), Filters.eq("age", 65));

        FindIterable<Document> documents = tb_hero.find(condition);

        MongoCursor<Document> iterator = documents.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
  • or条件查询
    @Test
    public void findQueryMulti3() {
        Bson condition = Filters.or(Filters.eq("name", "鲁智深"), Filters.eq("age", 43));

        FindIterable<Document> documents = tb_hero.find(condition);

        MongoCursor<Document> iterator = documents.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
  • in条件查询
    @Test
    public void findQueryMulti4() {

        List<Integer> idList = new ArrayList<Integer>();
        idList.add(43);
        idList.add(65);
        idList.add(23);

        BasicDBObject inQuery = new BasicDBObject();
        inQuery.put("age", new BasicDBObject("$in", idList));

        FindIterable<Document> documents = tb_hero.find(inQuery);

        MongoCursor<Document> iterator = documents.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

6、删除文档

  • 删除符合条件的第一条
    @Test
    public void deleteOne() {
        tb_hero.deleteOne(Filters.eq("age", 33));
    }
  • 删除符合条件的所有文档
    @Test
    public void deleteMany() {
        tb_hero.deleteMany(Filters.eq("age", 33));
    }

7、需要登录的连接

ServerAddress serverAddress = new ServerAddress("192.168.248.128", 27017);
List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
MongoCredential mc = MongoCredential.createScramSha1Credential("readuser","sang","123".toCharArray());
credentialsList.add(mc);
MongoClient client = new MongoClient(serverAddress,credentialsList);
MongoDatabase sang = client.getDatabase("sang");
c = sang.getCollection("c1");

MongoCredential是一个凭证,第一个参数为用户名,第二个参数是要在哪个数据库中验证,第三个参数是密码的char数组,然后将登录地址封装成一个ServerAddress,最后将两个参数都传入MongoClient中实现登录功能。

8、连接选项

ServerAddress serverAddress = new ServerAddress("192.168.248.128", 27017);
List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
MongoCredential mc = MongoCredential.createScramSha1Credential("rwuser","sang","123".toCharArray());
credentialsList.add(mc);
MongoClientOptions options = MongoClientOptions.builder()
        //设置连接超时时间为10s
        .connectTimeout(1000*10)
        //设置最长等待时间为10s
        .maxWaitTime(1000*10)
        .build();
MongoClient client = new MongoClient(serverAddress,credentialsList,options);
MongoDatabase sang = client.getDatabase("sang");
c = sang.getCollection("c1");