JavaApi操作MongoDB

紅丶發表於2020-10-21

本文演示了,如何連線到MongoDB,如何選擇資料庫、表,進行查詢的操作。

pom檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sunyuqi.mongodb</groupId>
    <artifactId>java-mongodb</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-sync</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
    </dependencies>
</project>

CURD操作

package com.sunyuqi.mongodb;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;

import java.util.function.Consumer;

import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Projections.*;
import static com.mongodb.client.model.Sorts.*;

public class TestMongoDB {

    MongoCollection<Document> collection;

    @Before
    public void init() {
        // 建立連線
        MongoClient mongoClient = MongoClients.create("mongodb://192.168.130.128:27017");

        // 選擇資料庫
        MongoDatabase database = mongoClient.getDatabase("testdb");

        // 選擇表
        collection = database.getCollection("user");
    }

    // 查詢age<=50並且id>=100的使用者資訊,並且按照id倒序排序,只返回id,age欄位,不返回_id欄位
    @Test
    public void testQuery() {
        this.collection.find(
                and(
                        lte("age", 30),
                        gte("id", 100)
                )
        ).sort(descending("id"))
                .projection(fields(include("id", "age"),
                        excludeId()))
                .forEach((Consumer<? super Document>) document -> {
                    System.out.println(document.toJson());
                });
    }

    // 插入資料
    @Test
    public void testInsert(){
        Document document = new Document();
        document.append("id", 1000);
        document.append("username", "張三");
        document.append("age", 30);
        this.collection.insertOne(document);

        // 查詢該資料
        this.collection.find(eq("id", 1000)).forEach((Consumer<? super Document>) document1 -> {
            System.out.println(document1.toJson());
        });
    }

    // 更新資料
    @Test
    public void testUpdate(){
        UpdateResult updateResult = this.collection.updateOne(eq("id", 1000), Updates.set("age", 40));
        System.out.println(updateResult);

        // 查詢該資料
        this.collection.find(eq("id", 1000)).forEach((Consumer<? super Document>) document1 -> {
            System.out.println(document1.toJson());
        });
    }
    // 刪除資料
    @Test
    public void testDelete(){
        DeleteResult deleteResult = this.collection.deleteMany(eq("age", 25));
        System.out.println(deleteResult);
    }
}

物件導向操作

前面對MongoDB的操作都是基於Document物件操作,操作略顯繁瑣,下面我們通過物件導向的方式進行操作。 建立User、Address物件:

package com.sunyuqi.mongodb.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.bson.types.ObjectId;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private ObjectId id;
    private String name;
    private int age;
    private Address address;
}

User中有一個欄位為Address,該類定義如下

package com.sunyuqi.mongodb.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Address {
    private String street;
    private String city;
    private String zip;
}

測試物件的CURD

package com.sunyuqi.mongodb;

import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.sunyuqi.mongodb.pojo.Address;
import com.sunyuqi.mongodb.pojo.User;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.types.ObjectId;
import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;

public class TestUser {

    MongoCollection<User> objectCollection;

    @Before
    public void init() {
        //定義物件的解碼註冊器
        CodecRegistry pojoCodecRegistry = CodecRegistries.
                fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
                        CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build())
                );
        // 建立連線
        MongoClient mongoClient = MongoClients.create("mongodb://192.168.130.128:27017");
        // 選擇資料庫 並且 註冊解碼器
        MongoDatabase mongoDatabase = mongoClient.getDatabase("testdb")
                .withCodecRegistry(pojoCodecRegistry);
        // 選擇表
        this.objectCollection = mongoDatabase
                .getCollection("user_detail", User.class);
    }
    // 插入一條
    @Test
    public void testInsert() {
        User user = new User(ObjectId.get(), "張三", 21,new Address("人民路", "上海市", "123456"));
        this.objectCollection.insertOne(user);
        System.out.println("插入資料成功");
    }

    // 批量插入
    @Test
    public void testInserts() {
        List<User> userList = Arrays.asList(
                new User(ObjectId.get(), "張三", 20, new Address("上海北路", "上海市", "123456")),
                new User(ObjectId.get(), "李四", 21, new Address("北京西路", "北京市", "222222")),
                new User(ObjectId.get(), "王五", 22, new Address("南京東路", "南京市", "333333")),
                new User(ObjectId.get(), "趙六", 23, new Address("陝西南路", "陝西市", "444444")),
                new User(ObjectId.get(), "孫七", 24, new Address("南京西路", "南京市", "555555")));
        this.objectCollection.insertMany(userList);
        System.out.println("插入資料成功");
    }

    // 查詢
    @Test
    public void testQuery() {
        this.objectCollection.find(eq("name", "張三"))
                .forEach((Consumer<? super User>) user -> {
                    System.out.println(user);
                });
    }
    // 更新
    @Test
    public void testUpdate() {
        UpdateResult updateResult =
                this.objectCollection.updateMany(eq("name", "張三"), set("age", 22));
        System.out.println(updateResult);
    }
    // 刪除
    @Test
    public void testDelete() {
        DeleteResult deleteResult =
                this.objectCollection.deleteMany(eq("name", "張三"));
        System.out.println(deleteResult);
    }

}

相關文章