MongoDB使用C驱动基本的CRUD操作

查找文档

要使用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
", 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-driverincludelibbson-1.0 /IC:mongo-c-driverincludelibmongoc-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
", 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-driverincludelibbson-1.0 /IC:mongo-c-driverincludelibmongoc-1.0 find-specific.c
C:> find-specific
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }