Java連接MongoDB實例

目錄

1 Java連接

1.1 maven依賴

1.2 客戶端代碼


筆者所用的MongoDB的版本是4.2.6。


1 Java連接

1.1 maven依賴

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
            <version>3.12.4</version>
        </dependency>

1.2 客戶端代碼

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;

/**
 * MongoDB客戶端
 *
 * @author Robert Hou
 * @date 2020年05月08日 22:35
 **/
public class MongoDBClient {

    private static final String MONGODB_URL = "mongodb://127.0.0.1:27017";

    private MongoDBClient() {
    }

    public static void main(String[] args) {
        MongoClientURI mongoClientURI = new MongoClientURI(MONGODB_URL);
        //取得MongoDB客戶端
        MongoClient mongoClient = new MongoClient(mongoClientURI);

        //取得test庫下的Product集合
        MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("Product");
        //創建文檔
        List<Document> documents = new ArrayList<>();
        Document document1 = new Document("Name", "Robert Hou")
                .append("Gender", "Male")
                .append("Tel", "18500000000")
                .append("Location", new Document("City", "Beijing").append("District", "Fengtai"));
        documents.add(document1);
        Document document2 = new Document("Name", "Tony")
                .append("Gender", "Male")
                .append("Tel", "13400000000")
                .append("Location", new Document("Province", "Guangxi").append("City", "Nanning"));
        documents.add(document2);
        collection.insertMany(documents);
        //修改文檔內容
        Document document3 = new Document("$set", new Document("Tel", "13400000001"));
        collection.updateMany(Filters.eq("Name", "Tony"), document3);
        //查詢全部文檔
        for (Document cur : collection.find()) {
            System.out.println(cur.toJson());
        }

        mongoClient.close();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章