欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java中連接Mongodb進行增刪改查的操作詳解

 更新時間:2024年06月07日 08:57:39   作者:小劉同學(xué)要加油呀  
MongoDB是一個基于分布式文件存儲的數(shù)據(jù)庫,由C++語言編寫,旨在為WEB應(yīng)用提供可擴展的高性能數(shù)據(jù)存儲解決方案,本文給大家介紹了Java中連接Mongodb進行操作,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下

1.引入Java驅(qū)動依賴

注意:啟動服務(wù)的時候需要加ip綁定
需要引入依賴

<dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongodb-driver-sync</artifactId>
      <version>5.1.0</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mongodb/bson -->
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>bson</artifactId>
      <version>5.1.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver-core -->
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongodb-driver-core</artifactId>
      <version>5.1.0</version>
    </dependency>

2.快速開始

2.1 先在monsh連接建立collection

db.players.insertOne({name:"palyer1",height:181,weigh:90})
{
  acknowledged: true,
  insertedId: ObjectId('665c5e0a522ef6dba6a26a13')
}
test> db.players.insertOne({name:"palyer2",height:190,weigh:100})
{
  acknowledged: true,
  insertedId: ObjectId('665c5e18522ef6dba6a26a14')
}
test> db.players.find()
[
  {
    _id: ObjectId('665c5e0a522ef6dba6a26a13'),
    name: 'player1',
    height: 181,
    weigh: 90
  },
  {
    _id: ObjectId('665c5e18522ef6dba6a26a14'),
    name: 'player2',
    height: 190,
    weigh: 100
  }
]

2.2 java中快速開始

public class QuickStart {

    public static void main(String[] args) {
        // 連接的url
        String uri = "mongodb://node02:27017";
        try (MongoClient mongoClient = MongoClients.create(uri)) {
            MongoDatabase database = mongoClient.getDatabase("test");
            MongoCollection<Document> collection = database.getCollection("players");
            Document doc = collection.find(eq("name", "palyer2")).first();
            if (doc != null) {
                //{"_id": {"$oid": "665c5e18522ef6dba6a26a14"}, "name": "palyer2", "height": 190, "weigh": 100}
                System.out.println(doc.toJson());
            } else {
                System.out.println("No matching documents found.");
            }
        }
    }

}

2.3 Insert a Document

 @Test
    public void InsertDocument()
    {
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("map");
        try {
            // 插入地圖文檔
            InsertOneResult result = collection.insertOne(new Document()
                    .append("_id", new ObjectId())
                    .append("name", "beijing")
                    .append("longitude", "40°N")
                    .append("latitude", "116°E"));
            //打印文檔的id
            //Success! Inserted document id: BsonObjectId{value=665c6424a080bb466d32e645}
            System.out.println("Success! Inserted document id: " + result.getInsertedId());
            // Prints a message if any exceptions occur during the operation
        } catch (MongoException me) {
            System.err.println("Unable to insert due to an error: " + me);
        }

2.4 Update a Document

 @Test
    public void UpdateDocument(){
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("map");
        //構(gòu)造更新條件
        Document query = new Document().append("name",  "beijing");
        // 指定更新的字段
        Bson updates = Updates.combine(
                Updates.set("longitude", "40.0N"),
                Updates.set("latitude", "116.0E")
        );
        // Instructs the driver to insert a new document if none match the query
        UpdateOptions options = new UpdateOptions().upsert(true);
        try {
            // 更新文檔
            UpdateResult result = collection.updateOne(query, updates, options);
            // Prints the number of updated documents and the upserted document ID, if an upsert was performed
            System.out.println("Modified document count: " + result.getModifiedCount());
            System.out.println("Upserted id: " + result.getUpsertedId());

        } catch (MongoException me) {
            System.err.println("Unable to update due to an error: " + me);
        }
    }

2.5 Find a Document

 @Test
    public void testFindDocuments(){
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("map");
        // 創(chuàng)建檢索條件
        /*Bson projectionFields = Projections.fields(
                Projections.include("name", "shanghai"),
                Projections.excludeId());*/
        // 匹配過濾檢索文檔
        MongoCursor<Document> cursor = collection.find(eq("name", "shanghai"))
                //.projection(projectionFields)
                .sort(Sorts.descending("longitude")).iterator();
        // 打印檢索到的文檔
        try {
            while(cursor.hasNext()) {
                System.out.println(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }
    }

2.6 Delete a Document

 @Test
    public void DeleteDocument(){
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("map");
        Bson query = eq("name", "shanghai");
        try {
            // 刪除名字為shanghai的地圖
            DeleteResult result = collection.deleteOne(query);
            System.out.println("Deleted document count: " + result.getDeletedCount());
            // 打印異常消息
        } catch (MongoException me) {
            System.err.println("Unable to delete due to an error: " + me);
        }
    }

到此這篇關(guān)于Java中連接Mongodb進行增刪改查的操作詳解的文章就介紹到這了,更多相關(guān)Java連接Mongodb操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java Swing程序設(shè)計實戰(zhàn)

    Java Swing程序設(shè)計實戰(zhàn)

    今天教大家怎么用JavaSwing工具包實現(xiàn)一個程序的界面設(shè)計,文中有非常詳細(xì)的代碼示例及注釋,對正在學(xué)習(xí)Java的小伙伴們很有幫助,需要的朋友可以參考下
    2021-05-05
  • Java實現(xiàn)的Excel列號數(shù)字與字母互相轉(zhuǎn)換功能

    Java實現(xiàn)的Excel列號數(shù)字與字母互相轉(zhuǎn)換功能

    這篇文章主要介紹了Java實現(xiàn)的Excel列號數(shù)字與字母互相轉(zhuǎn)換功能,涉及java針對Excel相關(guān)數(shù)值與字符串操作技巧,需要的朋友可以參考下
    2018-03-03
  • Spring?Cloud?Gateway?整合?knife4j?聚合接口文檔功能

    Spring?Cloud?Gateway?整合?knife4j?聚合接口文檔功能

    這篇文章主要介紹了Spring?Cloud?Gateway?整合?knife4j?聚合接口文檔的相關(guān)知識,我們可以基于?Spring?Cloud?Gateway?網(wǎng)關(guān)?+?nacos?+?knife4j?對所有微服務(wù)項目的接口文檔進行聚合,從而實現(xiàn)我們想要的文檔管理功能,需要的朋友可以參考下
    2022-02-02
  • java并發(fā)編程工具類PriorityBlockingQueue優(yōu)先級隊列

    java并發(fā)編程工具類PriorityBlockingQueue優(yōu)先級隊列

    這篇文章主要為大家介紹了java并發(fā)編程工具類PriorityBlockingQueue優(yōu)先級隊列的方法示例應(yīng)用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步
    2022-03-03
  • Eclipse設(shè)置斷點調(diào)試的方法

    Eclipse設(shè)置斷點調(diào)試的方法

    這篇文章主要介紹了Eclipse斷點調(diào)試的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • 一文了解SpringBoot是如何連接數(shù)據(jù)庫的

    一文了解SpringBoot是如何連接數(shù)據(jù)庫的

    Spring Boot提供了一系列的開箱即用的功能和特性,使得開發(fā)人員可以快速構(gòu)建和部署應(yīng)用程序,下面這篇文章主要給大家介紹了關(guān)于SpringBoot是如何連接數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下
    2023-06-06
  • Springboot2.x結(jié)合Mabatis3.x下Hikari連接數(shù)據(jù)庫報超時錯誤

    Springboot2.x結(jié)合Mabatis3.x下Hikari連接數(shù)據(jù)庫報超時錯誤

    本文針對Springboot2.x與Mybatis3.x結(jié)合使用時,Hikari連接數(shù)據(jù)庫出現(xiàn)超時錯誤的問題進行了深入分析,并提供了一系列有效的解決方法,感興趣的可以了解一下
    2023-11-11
  • 關(guān)于springboot集成swagger及knife4j的增強問題

    關(guān)于springboot集成swagger及knife4j的增強問題

    這篇文章主要介紹了springboot集成swagger以及knife4j的增強,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-03-03
  • Java數(shù)據(jù)結(jié)構(gòu)中關(guān)于AVL樹的實現(xiàn)方法詳解

    Java數(shù)據(jù)結(jié)構(gòu)中關(guān)于AVL樹的實現(xiàn)方法詳解

    這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)中關(guān)于AVL樹的實現(xiàn)方法,AVL樹是高度平衡的二叉樹,它的特點是AVL樹中任何節(jié)點的兩個子樹的高度最大差別為1,本文主要給大家介紹了Java語言如何實現(xiàn)AVL樹,需要的朋友可以參考下
    2024-02-02
  • Java ArrayList與LinkedList使用方法詳解

    Java ArrayList與LinkedList使用方法詳解

    Java中容器對象主要用來存儲其他對象,根據(jù)實現(xiàn)原理不同,主要有3類常用的容器對象:ArrayList使用數(shù)組結(jié)構(gòu)存儲容器中的元素、LinkedList使用鏈表結(jié)構(gòu)存儲容器中的元素
    2022-11-11

最新評論