最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java中連接Mongodb進(jìn)行增刪改查的操作詳解

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

1.引入Java驅(qū)動(dòng)依賴(lài)

注意:?jiǎn)?dòng)服務(wù)的時(shí)候需要加ip綁定
需要引入依賴(lài)

<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.快速開(kāi)始

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中快速開(kāi)始

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());*/
        // 匹配過(guò)濾檢索文檔
        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進(jìn)行增刪改查的操作詳解的文章就介紹到這了,更多相關(guān)Java連接Mongodb操作內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java后端必會(huì)Linux常用命令之一篇搞懂日志、進(jìn)程、端口、部署

    Java后端必會(huì)Linux常用命令之一篇搞懂日志、進(jìn)程、端口、部署

    掌握Linux命令行是開(kāi)發(fā)者的必備技能,本文用最簡(jiǎn)方式梳理高頻基礎(chǔ)命令,每個(gè)命令配常用示例,適合新手快速查閱,這篇文章主要介紹了Java后端必會(huì)Linux常用命令之一篇搞懂日志、進(jìn)程、端口、部署的相關(guān)資料,需要的朋友可以參考下
    2026-05-05
  • SpringBoot實(shí)現(xiàn)防重放攻擊的五種方案

    SpringBoot實(shí)現(xiàn)防重放攻擊的五種方案

    在項(xiàng)目開(kāi)發(fā)中,重放攻擊(Replay?Attack)是一種常見(jiàn)的攻擊手段,攻擊者截獲有效請(qǐng)求后重新發(fā)送給服務(wù)器,以達(dá)到未授權(quán)訪(fǎng)問(wèn)、重復(fù)交易或身份冒充等目的,本文將介紹五種在SpringBoot應(yīng)用中實(shí)現(xiàn)防重放攻擊的方案,需要的朋友可以參考下
    2025-06-06
  • 最新評(píng)論

    饶河县| 延边| 巴塘县| 探索| 泽普县| 托里县| 竹北市| 肇源县| 辽中县| 通道| 临夏市| 松潘县| 南召县| 砀山县| 肃宁县| 久治县| 遂宁市| 凯里市| 德州市| 舞阳县| 牙克石市| 宜兰县| 开封县| 土默特右旗| 合水县| 清丰县| 右玉县| 资中县| 繁峙县| 临高县| 洪雅县| 卢龙县| 宜昌市| 武定县| 武夷山市| 乌苏市| 达拉特旗| 孟州市| 中江县| 阜阳市| 县级市|