Docs 菜单

Docs 主页开发应用程序MongoDB 驱动程序C 驱动程序

教程

在此页面上

  • 正在安装
  • 启动 MongoDB
  • 在 C 程序中包含并链接 libmongoc
  • 包含 mongoc.h
  • CMake
  • pkg-config
  • 手动指定标头和包含路径
  • 在 Microsoft Visual Studio 项目中使用 libmongoc
  • 建立连接
  • 创建 BSON 文档
  • 附加 BSON
  • 使用 BCON
  • 从 JSON 创建 BSON
  • 基本增删改查操作
  • 插入文档
  • 查找文档
  • 更新文档
  • 删除文档
  • 盘点文档
  • 执行命令
  • 线程
  • 后续步骤

本指南简要介绍了 MongoDB C 驱动程序。

有关 C API 的更多信息,请参阅 API。

有关在特定平台上安装 MongoDB C 驱动程序的详细说明,请参阅安装指南。

要运行本教程中的示例,必须在默认端口27017上的 localhost上安装并运行 MongoDB。要检查它是否已启动并运行,请使用 MongoDB Shell 连接到它。

$ mongosh --host localhost --port 27017 --quiet
Enterprise rs0 [direct: primary] test> db.version()
7.0.0
>

libmongoc 的所有函数和类型都在一个头文件中可用。只需包含mongoc/mongoc.h即可:

#include <mongoc/mongoc.h>

libmongoc 安装包括 CMake 配置文件包 ,这样您就可以使用 CMake 的 find_package 命令导入 libmongoc 的 CMake 目标并链接到 libmongoc(作为共享库):

CMakeLists.txt
# Specify the minimum version you require.
find_package (mongoc-1.0 1.7 REQUIRED)
# The "hello_mongoc.c" sample program is shared among four tests.
add_executable (hello_mongoc ../../hello_mongoc.c)
target_link_libraries (hello_mongoc PRIVATE mongo::mongoc_shared)

您也可以使用 libmongoc 作为静态库:使用mongo::mongoc_static CMake 目标:

# Specify the minimum version you require.
find_package (mongoc-1.0 1.7 REQUIRED)
# The "hello_mongoc.c" sample program is shared among four tests.
add_executable (hello_mongoc ../../hello_mongoc.c)
target_link_libraries (hello_mongoc PRIVATE mongo::mongoc_static)

如果您不使用 CMake,请使用 pkg-config 在命令行中设置标头和库路径:

gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags libmongoc-1.0)

或者静态链接到 libmongoc:

gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags libmongoc-static-1.0)

如果您不使用 CMake 或 pkg-config,则可以手动管理路径和库。

$ gcc -o hello_mongoc hello_mongoc.c \
-I/usr/local/include/libbson-1.0 -I/usr/local/include/libmongoc-1.0 \
-lmongoc-1.0 -lbson-1.0
$ ./hello_mongoc
{ "ok" : 1.000000 }

对于 Windows 用户,可以使用以下命令编译和运行代码。 (假设 MongoDB C 驱动程序已安装到C:\mongo-c-driver ;根据需要更改包含目录。)

C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 hello_mongoc.c
C:\> hello_mongoc
{ "ok" : 1.000000 }

请参阅libmongoc 和 Visual Studio 指南。

使用 mongoc_client_t 访问 MongoDB 。它按需透明地连接到独立服务器、副本集和分片集群。要对数据库或集合执行操作,请创建 mongoc_database_t mongoc_collection_t mongoc_client_t 中的结构体。

在应用程序启动时,调用 mongoc_init 在任何其他 libmongoc 函数之前。最后,按照与构造函数相反的顺序,为每个集合、数据库或客户端句柄调用相应的销毁函数。调用 mongoc_cleanup 在退出之前。

以下示例在localhost上建立与独立服务器的连接,将客户端应用程序注册为“connect-example”,并执行简单的命令。

有关数据库操作的更多信息,请参阅“增删改查操作”和“执行命令”部分。连接到副本集和分片集群的示例可以在“高级连接”页面中找到,而数据压缩的示例可以在“数据压缩”页面中找到。

hello_mongoc.c
#include <mongoc/mongoc.h>
int
main (int argc, char *argv[])
{
const char *uri_string = "mongodb://localhost:27017";
mongoc_uri_t *uri;
mongoc_client_t *client;
mongoc_database_t *database;
mongoc_collection_t *collection;
bson_t *command, reply, *insert;
bson_error_t error;
char *str;
bool retval;
/*
* Required to initialize libmongoc's internals
*/
mongoc_init ();
/*
* Optionally get MongoDB URI from command line
*/
if (argc > 1) {
uri_string = argv[1];
}
/*
* Safely create a MongoDB URI object from the given string
*/
uri = mongoc_uri_new_with_error (uri_string, &error);
if (!uri) {
fprintf (stderr,
"failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
error.message);
return EXIT_FAILURE;
}
/*
* Create a new client instance
*/
client = mongoc_client_new_from_uri (uri);
if (!client) {
return EXIT_FAILURE;
}
/*
* Register the application name so we can track it in the profile logs
* on the server. This can also be done from the URI (see other examples).
*/
mongoc_client_set_appname (client, "connect-example");
/*
* Get a handle on the database "db_name" and collection "coll_name"
*/
database = mongoc_client_get_database (client, "db_name");
collection = mongoc_client_get_collection (client, "db_name", "coll_name");
/*
* Do work. This example pings the database, prints the result as JSON and
* performs an insert
*/
command = BCON_NEW ("ping", BCON_INT32 (1));
retval = mongoc_client_command_simple (client, "admin", command, NULL, &reply, &error);
if (!retval) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
str = bson_as_json (&reply, NULL);
printf ("%s\n", str);
insert = BCON_NEW ("hello", BCON_UTF8 ("world"));
if (!mongoc_collection_insert_one (collection, insert, NULL, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
}
bson_destroy (insert);
bson_destroy (&reply);
bson_destroy (command);
bson_free (str);
/*
* Release our handles and clean up libmongoc
*/
mongoc_collection_destroy (collection);
mongoc_database_destroy (database);
mongoc_uri_destroy (uri);
mongoc_client_destroy (client);
mongoc_cleanup ();
return EXIT_SUCCESS;
}

文档以 MongoDB 的数据格式 BSON 存储。 C 驱动程序使用libbson创建 BSON 文档。有几种方法可以构造它们:附加键值对、使用 BCON 或解析 JSON。

一份 BSON 文档,表示为 bson_t 在代码中,可以使用 libbson 的追加函数一次构造一个字段。

例如,要创建如下文档:

{
born : ISODate("1906-12-09"),
died : ISODate("1992-01-01"),
name : {
first : "Grace",
last : "Hopper"
},
languages : [ "MATH-MATIC", "FLOW-MATIC", "COBOL" ],
degrees: [ { degree: "BA", school: "Vassar" }, { degree: "PhD", school: "Yale" } ]
}

使用以下代码:

#include <bson/bson.h>
int
main (void)
{
struct tm born = {0};
struct tm died = {0};
const char *lang_names[] = {"MATH-MATIC", "FLOW-MATIC", "COBOL"};
const char *schools[] = {"Vassar", "Yale"};
const char *degrees[] = {"BA", "PhD"};
uint32_t i;
bson_t *document;
bson_t child;
bson_array_builder_t *bab;
char *str;
document = bson_new ();
/*
* Append { "born" : ISODate("1906-12-09") } to the document.
* Passing -1 for the length argument tells libbson to calculate the
* string length.
*/
born.tm_year = 6; /* years are 1900-based */
born.tm_mon = 11; /* months are 0-based */
born.tm_mday = 9;
bson_append_date_time (document, "born", -1, mktime (&born) * 1000);
/*
* Append { "died" : ISODate("1992-01-01") } to the document.
*/
died.tm_year = 92;
died.tm_mon = 0;
died.tm_mday = 1;
/*
* For convenience, this macro passes length -1 by default.
*/
BSON_APPEND_DATE_TIME (document, "died", mktime (&died) * 1000);
/*
* Append a subdocument.
*/
BSON_APPEND_DOCUMENT_BEGIN (document, "name", &child);
BSON_APPEND_UTF8 (&child, "first", "Grace");
BSON_APPEND_UTF8 (&child, "last", "Hopper");
bson_append_document_end (document, &child);
/*
* Append array of strings. Generate keys "0", "1", "2".
*/
BSON_APPEND_ARRAY_BUILDER_BEGIN (document, "languages", &bab);
for (i = 0; i < sizeof lang_names / sizeof (char *); ++i) {
bson_array_builder_append_utf8 (bab, lang_names[i], -1);
}
bson_append_array_builder_end (document, bab);
/*
* Array of subdocuments:
* degrees: [ { degree: "BA", school: "Vassar" }, ... ]
*/
BSON_APPEND_ARRAY_BUILDER_BEGIN (document, "degrees", &bab);
for (i = 0; i < sizeof degrees / sizeof (char *); ++i) {
bson_array_builder_append_document_begin (bab, &child);
BSON_APPEND_UTF8 (&child, "degree", degrees[i]);
BSON_APPEND_UTF8 (&child, "school", schools[i]);
bson_array_builder_append_document_end (bab, &child);
}
bson_append_array_builder_end (document, bab);
/*
* Print the document as a JSON string.
*/
str = bson_as_canonical_extended_json (document, NULL);
printf ("%s\n", str);
bson_free (str);
/*
* Clean up allocated bson documents.
*/
bson_destroy (document);
return 0;
}

有关可以附加到 bson_t 的所有类型,请参阅 libbson 文档 。

BSON C 对象表示法(简称 BCON)是一种以更接近预期格式的方式构建 BSON 文档的替代方法。它的类型安全性不如 BSON 的附加函数,但代码更少。

#include <bson/bson.h>
int
main (int argc,
char *argv[])
{
struct tm born = { 0 };
struct tm died = { 0 };
bson_t *document;
char *str;
born.tm_year = 6;
born.tm_mon = 11;
born.tm_mday = 9;
died.tm_year = 92;
died.tm_mon = 0;
died.tm_mday = 1;
document = BCON_NEW (
"born", BCON_DATE_TIME (mktime (&born) * 1000),
"died", BCON_DATE_TIME (mktime (&died) * 1000),
"name", "{",
"first", BCON_UTF8 ("Grace"),
"last", BCON_UTF8 ("Hopper"),
"}",
"languages", "[",
BCON_UTF8 ("MATH-MATIC"),
BCON_UTF8 ("FLOW-MATIC"),
BCON_UTF8 ("COBOL"),
"]",
"degrees", "[",
"{", "degree", BCON_UTF8 ("BA"), "school", BCON_UTF8 ("Vassar"), "}",
"{", "degree", BCON_UTF8 ("PhD"), "school", BCON_UTF8 ("Yale"), "}",
"]");
/*
* Print the document as a JSON string.
*/
str = bson_as_canonical_extended_json (document, NULL);
printf ("%s\n", str);
bson_free (str);
/*
* Clean up allocated bson documents.
*/
bson_destroy (document);
return 0;
}

请注意,BCON 可以创建数组、子文档和任意字段。

对于 单个 文档,可以通过 bson_new_from_json 从 JSON 字符串创建 BSON。

#include <bson/bson.h>
int
main (int argc,
char *argv[])
{
bson_error_t error;
bson_t *bson;
char *string;
const char *json = "{\"name\": {\"first\":\"Grace\", \"last\":\"Hopper\"}}";
bson = bson_new_from_json ((const uint8_t *)json, -1, &error);
if (!bson) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
string = bson_as_canonical_extended_json (bson, NULL);
printf ("%s\n", string);
bson_free (string);
return 0;
}

要从 JSON 文档序列初始化 BSON,请使用 bson_json_reader_t。

本部分演示使用 C 驱动程序与 MongoDB 交互的基础知识。

要将文档插入到集合中,请首先通过mongoc_collection_t 获取mongoc_client_t 的句柄。然后,使用 mongoc_collection_insert_one 将 BSON 文档添加到集合中。此示例将插入到数据库“mydb”和集合“mycoll”中。

完成后,确保使用各自的销毁函数释放分配的结构。

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc,
char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_oid_t oid;
bson_t *doc;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/?appname=insert-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
doc = bson_new ();
bson_oid_init (&oid, NULL);
BSON_APPEND_OID (doc, "_id", &oid);
BSON_APPEND_UTF8 (doc, "hello", "world");
if (!mongoc_collection_insert_one (
collection, doc, NULL, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}

编译并运行代码:

$ gcc -o insert insert.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./insert

在 Windows 上:

C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 insert.c
C:\> insert

要验证插入是否成功,请连接 MongoDB Shell。

$ mongo
MongoDB shell version: 3.0.6
connecting to: test
> use mydb
switched to db mydb
> db.mycoll.find()
{ "_id" : ObjectId("55ef43766cb5f36a3bae6ee4"), "hello" : "world" }
>

要使用 C 驱动程序查询 MongoDB 集合,请使用函数 mongoc_collection_find_with_opts 。这将返回一个 游标 匹配文档。以下示例将遍历结果游标,并将匹配项作为stdout JSON 字符串打印到 。

使用文档作为查询说明符;例如,

{ "color" : "red" }

将匹配任何具有名为“color”且值为“red”的字段的文档。空文档{}可用于匹配所有文档。

第一个示例使用空查询说明符查找数据库“mydb”和集合“mycoll”中的所有文档。

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
mongoc_cursor_t *cursor;
const bson_t *doc;
bson_t *query;
char *str;
mongoc_init ();
client =
mongoc_client_new ("mongodb://localhost:27017/?appname=find-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
query = bson_new ();
cursor = mongoc_collection_find_with_opts (collection, query, NULL, NULL);
while (mongoc_cursor_next (cursor, &doc)) {
str = bson_as_canonical_extended_json (doc, NULL);
printf ("%s\n", str);
bson_free (str);
}
bson_destroy (query);
mongoc_cursor_destroy (cursor);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}

编译并运行代码:

$ gcc -o find find.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./find
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }

在 Windows 上:

C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 find.c
C:\> find
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }

要查找特定文档,请向query添加说明符。此示例添加了对BSON_APPEND_UTF8()的调用,以查找与{"hello" : "world"}匹配的所有文档。

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
mongoc_cursor_t *cursor;
const bson_t *doc;
bson_t *query;
char *str;
mongoc_init ();
client = mongoc_client_new (
"mongodb://localhost:27017/?appname=find-specific-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
query = bson_new ();
BSON_APPEND_UTF8 (query, "hello", "world");
cursor = mongoc_collection_find_with_opts (collection, query, NULL, NULL);
while (mongoc_cursor_next (cursor, &doc)) {
str = bson_as_canonical_extended_json (doc, NULL);
printf ("%s\n", str);
bson_free (str);
}
bson_destroy (query);
mongoc_cursor_destroy (cursor);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
$ gcc -o find-specific find-specific.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./find-specific
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 find-specific.c
C:\> find-specific
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }

此代码片段提供了使用 mongoc_collection_update_one 的示例 更新文档的字段。

以下示例使用“mydb”数据库,将示例文档插入“mycoll”集合。然后,使用其_id字段,将文档更新为不同的值和新字段。

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_collection_t *collection;
mongoc_client_t *client;
bson_error_t error;
bson_oid_t oid;
bson_t *doc = NULL;
bson_t *update = NULL;
bson_t *query = NULL;
mongoc_init ();
client =
mongoc_client_new ("mongodb://localhost:27017/?appname=update-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
bson_oid_init (&oid, NULL);
doc = BCON_NEW ("_id", BCON_OID (&oid), "key", BCON_UTF8 ("old_value"));
if (!mongoc_collection_insert_one (collection, doc, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
goto fail;
}
query = BCON_NEW ("_id", BCON_OID (&oid));
update = BCON_NEW ("$set",
"{",
"key",
BCON_UTF8 ("new_value"),
"updated",
BCON_BOOL (true),
"}");
if (!mongoc_collection_update_one (
collection, query, update, NULL, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
goto fail;
}
fail:
if (doc)
bson_destroy (doc);
if (query)
bson_destroy (query);
if (update)
bson_destroy (update);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}

编译并运行代码:

$ gcc -o update update.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./update

在 Windows 上:

C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 update.c
C:\> update
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }

要验证更新是否成功,请连接 MongoDB Shell。

$ mongo
MongoDB shell version: 3.0.6
connecting to: test
> use mydb
switched to db mydb
> db.mycoll.find({"updated" : true})
{ "_id" : ObjectId("55ef549236fe322f9490e17b"), "updated" : true, "key" : "new_value" }
>

此示例说明了如何使用 mongoc_collection_delete_one 删除文档。

以下代码将样本文档插入数据库“mydb”和集合“mycoll”中。然后,它会删除所有匹配{"hello" : "world"}的文档。

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_oid_t oid;
bson_t *doc;
mongoc_init ();
client =
mongoc_client_new ("mongodb://localhost:27017/?appname=delete-example");
collection = mongoc_client_get_collection (client, "test", "test");
doc = bson_new ();
bson_oid_init (&oid, NULL);
BSON_APPEND_OID (doc, "_id", &oid);
BSON_APPEND_UTF8 (doc, "hello", "world");
if (!mongoc_collection_insert_one (collection, doc, NULL, &error)) {
fprintf (stderr, "Insert failed: %s\n", error.message);
}
bson_destroy (doc);
doc = bson_new ();
BSON_APPEND_OID (doc, "_id", &oid);
if (!mongoc_collection_delete_one (
collection, doc, NULL, NULL, &error)) {
fprintf (stderr, "Delete failed: %s\n", error.message);
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}

编译并运行代码:

$ gcc -o delete delete.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./delete

在 Windows 上:

C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 delete.c
C:\> delete

使用 MongoDB Shell 证明已成功删除文档。

$ mongo
MongoDB shell version: 3.0.6
connecting to: test
> use mydb
switched to db mydb
> db.mycoll.count({"hello" : "world"})
0
>

计算 MongoDB 集合中的文档数量与执行查找操作类似。此示例计算数据库“mydb”和集合“mycoll”中与{"hello" : "world"}匹配的文档数量。

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_t *doc;
int64_t count;
mongoc_init ();
client =
mongoc_client_new ("mongodb://localhost:27017/?appname=count-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
doc = bson_new_from_json (
(const uint8_t *) "{\"hello\" : \"world\"}", -1, &error);
count = mongoc_collection_count (
collection, MONGOC_QUERY_NONE, doc, 0, 0, NULL, &error);
if (count < 0) {
fprintf (stderr, "%s\n", error.message);
} else {
printf ("%" PRId64 "\n", count);
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}

编译并运行代码:

$ gcc -o count count.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./count
1

在 Windows 上:

C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 count.c
C:\> count
1

该驱动程序提供了辅助函数,用于在客户端、数据库和集合结构上执行 MongoDB 命令。 _simple变体返回指示成功或失败的布尔值。

此示例对数据库“mydb”执行ping命令。

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (void)
{
mongoc_client_t *client;
bson_error_t error;
bson_t *command;
bson_t reply;
char *str;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/?appname=executing-example");
command = BCON_NEW ("ping", BCON_INT32 (1));
if (mongoc_client_command_simple (client, "mydb", command, NULL, &reply, &error)) {
str = bson_as_canonical_extended_json (&reply, NULL);
printf ("%s\n", str);
bson_free (str);
} else {
fprintf (stderr, "Failed to run command: %s\n", error.message);
}
bson_destroy (command);
bson_destroy (&reply);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}

编译并运行代码:

$ gcc -o executing executing.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./executing
{ "ok" : { "$numberDouble" : "1.0" }, "$clusterTime" : { "clusterTime" : { "$timestamp" : { "t" : 1682609211, "i" : 1 } }, "signature" : { "hash" : { "$binary" : { "base64" : "AAAAAAAAAAAAAAAAAAAAAAAAAAA=", "subType" : "00" } }, "keyId" : { "$numberLong" : "0" } } }, "operationTime" : { "$timestamp" : { "t" : 1682609211, "i" : 1 } } }

在 Windows 上:

C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 executing.c
C:\> executing
{ "ok" : { "$numberDouble" : "1.0" }, "$clusterTime" : { "clusterTime" : { "$timestamp" : { "t" : 1682609211, "i" : 1 } }, "signature" : { "hash" : { "$binary" : { "base64" : "AAAAAAAAAAAAAAAAAAAAAAAAAAA=", "subType" : "00" } }, "keyId" : { "$numberLong" : "0" } } }, "operationTime" : { "$timestamp" : { "t" : 1682609211, "i" : 1 } } }

MongoDB C 驱动程序在绝大多数操作中都是线程不感知的。这意味着由程序员来保证线程安全。

但是, mongoc_client_pool_t 是线程安全的,用于以线程安全的方式获取mongoc_client_t 。从池中检索客户端后,客户端结构应被视为由调用线程拥有。线程完成后,应将客户端放回池中。

example-pool.c
/* gcc example-pool.c -o example-pool $(pkg-config --cflags --libs
* libmongoc-1.0) */
/* ./example-pool [CONNECTION_STRING] */
#include <mongoc/mongoc.h>
#include <pthread.h>
#include <stdio.h>
static pthread_mutex_t mutex;
static bool in_shutdown = false;
static void *
worker (void *data)
{
mongoc_client_pool_t *pool = data;
mongoc_client_t *client;
bson_t ping = BSON_INITIALIZER;
bson_error_t error;
bool r;
BSON_APPEND_INT32 (&ping, "ping", 1);
while (true) {
client = mongoc_client_pool_pop (pool);
/* Do something with client. If you are writing an HTTP server, you
* probably only want to hold onto the client for the portion of the
* request performing database queries.
*/
r = mongoc_client_command_simple (client, "admin", &ping, NULL, NULL, &error);
if (!r) {
fprintf (stderr, "%s\n", error.message);
}
mongoc_client_pool_push (pool, client);
pthread_mutex_lock (&mutex);
if (in_shutdown || !r) {
pthread_mutex_unlock (&mutex);
break;
}
pthread_mutex_unlock (&mutex);
}
bson_destroy (&ping);
return NULL;
}
int
main (int argc, char *argv[])
{
const char *uri_string = "mongodb://127.0.0.1/?appname=pool-example";
mongoc_uri_t *uri;
bson_error_t error;
mongoc_client_pool_t *pool;
pthread_t threads[10];
unsigned i;
void *ret;
pthread_mutex_init (&mutex, NULL);
mongoc_init ();
if (argc > 1) {
uri_string = argv[1];
}
uri = mongoc_uri_new_with_error (uri_string, &error);
if (!uri) {
fprintf (stderr,
"failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
error.message);
return EXIT_FAILURE;
}
pool = mongoc_client_pool_new (uri);
mongoc_client_pool_set_error_api (pool, 2);
for (i = 0; i < 10; i++) {
pthread_create (&threads[i], NULL, worker, pool);
}
sleep (10);
pthread_mutex_lock (&mutex);
in_shutdown = true;
pthread_mutex_unlock (&mutex);
for (i = 0; i < 10; i++) {
pthread_join (threads[i], &ret);
}
mongoc_client_pool_destroy (pool);
mongoc_uri_destroy (uri);
mongoc_cleanup ();
return EXIT_SUCCESS;
}

要查找有关高级主题的信息,请浏览C 驱动程序指南的其余部分或MongoDB 官方文档

如需常见问题的帮助,请参阅故障排除页面。要报告错误或请求新功能,请按照以下说明进行操作。

← mongo-c-driver 平台支持