VC++ 实现连接到mongodb,和增删改查的例子代码
时间: 2024-03-06 15:47:30 浏览: 154
以下是一个连接到 MongoDB 数据库并进行增删改查操作的 VC++ 示例代码:
```c++
#include <iostream>
#include <mongoc.h>
int main(int argc, char* argv[])
{
mongoc_client_t* client;
mongoc_collection_t* collection;
mongoc_cursor_t* cursor;
bson_t* query;
bson_t* doc;
bson_error_t error;
const char* uri_string = "mongodb://localhost:27017";
const char* db_name = "mydb";
const char* collection_name = "mycollection";
mongoc_init();
client = mongoc_client_new(uri_string);
if (!client) {
std::cout << "Failed to parse URI." << std::endl;
return EXIT_FAILURE;
}
collection = mongoc_client_get_collection(client, db_name, collection_name);
// insert document
doc = bson_new();
BSON_APPEND_UTF8(doc, "name", "John");
BSON_APPEND_INT32(doc, "age", 25);
if (!mongoc_collection_insert_one(collection, doc, NULL, NULL, &error)) {
std::cout << "Insert failed: " << error.message << std::endl;
return EXIT_FAILURE;
}
bson_destroy(doc);
// find document
query = bson_new();
BSON_APPEND_UTF8(query, "name", "John");
cursor = mongoc_collection_find_with_opts(collection, query, NULL, NULL);
const bson_t* doc_result;
while (mongoc_cursor_next(cursor, &doc_result)) {
char* str = bson_as_json(doc_result, NULL);
std::cout << str << std::endl;
bson_free(str);
}
bson_destroy(query);
mongoc_cursor_destroy(cursor);
// update document
query = bson_new();
BSON_APPEND_UTF8(query, "name", "John");
doc = bson_new();
BSON_APPEND_UTF8(doc, "$set", "{ age: 26 }");
if (!mongoc_collection_update_one(collection, query, doc, NULL, NULL, &error)) {
std::cout << "Update failed: " << error.message << std::endl;
return EXIT_FAILURE;
}
bson_destroy(query);
bson_destroy(doc);
// delete document
query = bson_new();
BSON_APPEND_UTF8(query, "name", "John");
if (!mongoc_collection_delete_one(collection, query, NULL, &error)) {
std::cout << "Delete failed: " << error.message << std::endl;
return EXIT_FAILURE;
}
bson_destroy(query);
mongoc_collection_destroy(collection);
mongoc_client_destroy(client);
mongoc_cleanup();
return EXIT_SUCCESS;
}
```
需要注意的是,这里使用的是 MongoDB C Driver 进行操作,需要在项目中引入相应的库文件和头文件。另外,这里只是一个简单的示例,实际使用时还需要进行错误处理和资源释放等操作。
阅读全文
相关推荐


















