[c++] C++에서 MongoDB에서 데이터 갱신하기

MongoDB는 C++ 언어로 작성된 애플리케이션에서 데이터를 갱신하는 데 사용될 수 있습니다.

MongoDB C++ 드라이버 설치하기

먼저, C++ 언어로 MongoDB를 조작하기 위해서는 MongoDB C++ 드라이버를 설치해야 합니다. 해당 드라이버는 C++에서 MongoDB와의 상호 작용을 용이하게 해줍니다.

데이터 갱신

MongoDB에서 데이터를 갱신하기 위해서는 update_one 또는 update_many 함수를 사용할 수 있습니다.

update_one 함수 사용 예제

#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <bsoncxx/builder/stream/document.hpp>

mongocxx::instance inst{};
mongocxx::client conn{mongocxx::uri{}};
auto collection = conn["testdb"]["testcollection"];

auto filter = bsoncxx::builder::stream::document{} << "name" << "Alice" << finalize;
auto update = bsoncxx::builder::stream::document{} << "$set" << bsoncxx::builder::stream::open_document
                                                  << "age" << 30
                                                  << "country" << "UK"
                                                  << bsoncxx::builder::stream::close_document << finalize;

collection.update_one(filter.view(), update.view());

위의 예제는 name이 “Alice”인 문서의 age를 30으로, country를 “UK”로 갱신하는 예제입니다.

update_many 함수 사용 예제

auto filter = bsoncxx::builder::stream::document{} << "status" << "Pending" << finalize;
auto update = bsoncxx::builder::stream::document{} << "$set" << bsoncxx::builder::stream::open_document
                                                  << "status" << "Processed"
                                                  << bsoncxx::builder::stream::close_document << finalize;

collection.update_many(filter.view(), update.view());

위의 예제는 status가 “Pending”인 문서들의 status를 “Processed”로 일괄 갱신하는 예제입니다.

마무리

위 예제는 C++에서 MongoDB 데이터를 갱신하는 간단한 방법을 보여줍니다. 해당 코드를 참고하여 원하는 작업에 맞게 수정하여 사용할 수 있습니다. MongoDB C++ 드라이버의 API 문서를 참고하여 더 많은 기능을 확인할 수 있습니다.

참고 자료: