MongoDBClient詳解

一、什麼是MongoDBClient

MongoDBClient是MongoDB官方提供的C++17客戶端庫,用來連接、操作MongoDB資料庫。MongoDBClient提供了多種API,包括CRUD操作、聚合查詢、地理空間索引等。

二、如何使用MongoDBClient連接資料庫

使用MongoDBClient連接資料庫分為三個步驟:創建連接、指定資料庫、驗證身份。

#include 
#include 

int main() {
    // 創建實例
    mongocxx::instance inst{};

    // 創建客戶端
    mongocxx::client conn{ mongocxx::uri{} };

    // 指定資料庫和集合
    auto db = conn["dbname"];
    auto coll = db["collectionname"];

    // 憑據驗證
    auto builder = bsoncxx::builder::stream::document{};
    bsoncxx::document::value doc_value = builder
        << "user" << "myuser"
        << "pwd" << "mypwd"
        << bsoncxx::builder::stream::finalize;
    auto creds = mongocxx::uri::auth_mechanism_properties{}
        .add("SCRAM-SHA-1", bsoncxx::types::b_document{doc_value});

    // 連接MongoDB
    conn.authenticate(creds);

    return 0;
}

三、CRUD操作

1. 插入數據

MongoDBClient提供了多種插入數據的API,最常用的是insert_one()和insert_many()。

// 插入單條數據
auto builder = bsoncxx::builder::stream::document{};
bsoncxx::document::value doc_value = builder
    << "name" << "Tom"
    << "age" << 20
    << bsoncxx::builder::stream::finalize;
coll.insert_one(doc_value.view());

// 插入多條數據
std::vector docs;
for (int i = 0; i < 5; ++i) {
    auto builder = bsoncxx::builder::stream::document{};
    bsoncxx::document::value doc_value = builder
        << "name" << "Tom"
        << "age" << 20+i
        << bsoncxx::builder::stream::finalize;
    docs.push_back(doc_value);
}
coll.insert_many(docs);

2. 查詢數據

MongoDBClient提供了多種查詢數據的API,最常用的是find_one()和find()。

// 查詢單條數據
auto result = coll.find_one(
    make_document(kvp("name", "Tom"))
);
std::cout << bsoncxx::to_json(*result) << std::endl;

// 查詢多條數據
auto cursor = coll.find(
    make_document(kvp("age", make_document(kvp("$gte", 20))))
);
for (auto&& doc : cursor) {
    std::cout << bsoncxx::to_json(doc) << std::endl;
}

3. 修改數據

MongoDBClient提供了多種修改數據的API,最常用的是update_one()和update_many()。

// 修改單條數據
coll.update_one(
    make_document(kvp("name", "Tom")),
    make_document(kvp("$set", make_document(kvp("age", 30))))
);

// 修改多條數據
coll.update_many(
    make_document(kvp("name", "Tom")),
    make_document(kvp("$set", make_document(kvp("age", 30))))
);

4. 刪除數據

MongoDBClient提供了多種刪除數據的API,最常用的是delete_one()和delete_many()。

// 刪除單條數據
coll.delete_one(
    make_document(kvp("name", "Tom"))
);

// 刪除多條數據
coll.delete_many(
    make_document(kvp("name", "Tom"))
);

四、聚合查詢

MongoDBClient支持多種聚合查詢操作,如計算總數、去重、分組、排序等。

// 計算總數
auto total_cursor = coll.aggregate(
    make_array(bsoncxx::from_json(R"(
        { $count: "total" }
    )"))
);
auto total_view = total_cursor.begin()->view();
std::cout << bsoncxx::to_json(total_view) << std::endl;

// 去重
auto distinct_cursor = coll.aggregate(
    make_array(bsoncxx::from_json(R"(
        { $group: { _id: "$name" } },
        { $sort: { _id: 1 } }
    )"))
);
for (auto&& doc : distinct_cursor) {
    std::cout << bsoncxx::to_json(doc) << std::endl;
}

// 分組
auto group_cursor = coll.aggregate(
    make_array(bsoncxx::from_json(R"(
        { $group: { _id: "$name", count: { $sum: 1 } } },
        { $sort: { count: -1 } }
    )"))
);
for (auto&& doc : group_cursor) {
    std::cout << bsoncxx::to_json(doc) << std::endl;
}

五、地理空間索引

MongoDBClient支持地理空間索引,可以實現根據經緯度查詢附近的位置。

// 創建地理空間索引
auto index_spec = bsoncxx::builder::stream::document{};
bsoncxx::document::value index_value = index_spec
    << "loc" << "2dsphere" << bsoncxx::builder::stream::finalize;
bsoncxx::document::view index_view = index_value.view();
coll.create_index(index_view);

// 插入數據
auto doc_builder = bsoncxx::builder::stream::document{};
bsoncxx::document::value doc_value = doc_builder
    << "name" << "Tom"
    << "loc" << bsoncxx::builder::stream::open_document
            << "type" << "Point"
            << "coordinates" << bsoncxx::builder::stream::open_array
                << 116.3975 << 39.9085
            << bsoncxx::builder::stream::close_array
        << bsoncxx::builder::stream::close_document
    << bsoncxx::builder::stream::finalize;
coll.insert_one(doc_value.view());

// 查找附近的位置
auto nearby_cursor = coll.find(
    make_document(kvp("loc",
        make_document(kvp("$nearSphere",
            make_document(kvp("$geometry",
                make_document(kvp("type", "Point"),
                    kvp("coordinates", make_array(116.4038, 39.915))))
            ),
            kvp("$maxDistance", 5000)
        ))
     ))
);

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/187455.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-11-28 06:22
下一篇 2024-11-28 06:23

相關推薦

  • 神經網路代碼詳解

    神經網路作為一種人工智慧技術,被廣泛應用於語音識別、圖像識別、自然語言處理等領域。而神經網路的模型編寫,離不開代碼。本文將從多個方面詳細闡述神經網路模型編寫的代碼技術。 一、神經網…

    編程 2025-04-25
  • Linux sync詳解

    一、sync概述 sync是Linux中一個非常重要的命令,它可以將文件系統緩存中的內容,強制寫入磁碟中。在執行sync之前,所有的文件系統更新將不會立即寫入磁碟,而是先緩存在內存…

    編程 2025-04-25
  • MPU6050工作原理詳解

    一、什麼是MPU6050 MPU6050是一種六軸慣性感測器,能夠同時測量加速度和角速度。它由三個感測器組成:一個三軸加速度計和一個三軸陀螺儀。這個組合提供了非常精細的姿態解算,其…

    編程 2025-04-25
  • Java BigDecimal 精度詳解

    一、基礎概念 Java BigDecimal 是一個用於高精度計算的類。普通的 double 或 float 類型只能精確表示有限的數字,而對於需要高精度計算的場景,BigDeci…

    編程 2025-04-25
  • Python輸入輸出詳解

    一、文件讀寫 Python中文件的讀寫操作是必不可少的基本技能之一。讀寫文件分別使用open()函數中的’r’和’w’參數,讀取文件…

    編程 2025-04-25
  • nginx與apache應用開發詳解

    一、概述 nginx和apache都是常見的web伺服器。nginx是一個高性能的反向代理web伺服器,將負載均衡和緩存集成在了一起,可以動靜分離。apache是一個可擴展的web…

    編程 2025-04-25
  • C語言貪吃蛇詳解

    一、數據結構和演算法 C語言貪吃蛇主要運用了以下數據結構和演算法: 1. 鏈表 typedef struct body { int x; int y; struct body *nex…

    編程 2025-04-25
  • 詳解eclipse設置

    一、安裝與基礎設置 1、下載eclipse並進行安裝。 2、打開eclipse,選擇對應的工作空間路徑。 File -> Switch Workspace -> [選擇…

    編程 2025-04-25
  • Linux修改文件名命令詳解

    在Linux系統中,修改文件名是一個很常見的操作。Linux提供了多種方式來修改文件名,這篇文章將介紹Linux修改文件名的詳細操作。 一、mv命令 mv命令是Linux下的常用命…

    編程 2025-04-25
  • Python安裝OS庫詳解

    一、OS簡介 OS庫是Python標準庫的一部分,它提供了跨平台的操作系統功能,使得Python可以進行文件操作、進程管理、環境變數讀取等系統級操作。 OS庫中包含了大量的文件和目…

    編程 2025-04-25

發表回復

登錄後才能評論