连接到MongoDB
1
2
创建您的C驱动应用程序
将以下代码复制并粘贴到 quickstart.c
文件中,该文件查询 movies
集合在 sample_mflix
数据库中
int main (void) { const bson_t *doc; mongoc_init (); mongoc_client_t *client = mongoc_client_new ("<connection string>"); mongoc_collection_t *collection = mongoc_client_get_collection (client, "sample_mflix", "movies"); // Specify the query filter bson_t *query = BCON_NEW ("title", "The Shawshank Redemption"); mongoc_cursor_t *results = mongoc_collection_find_with_opts (collection, query, NULL, NULL); // Print the results while (mongoc_cursor_next (results, &doc)) { char* str = bson_as_canonical_extended_json (doc, NULL); printf ("%s\n", str); bson_free (str); } bson_destroy (query); mongoc_cursor_destroy (results); mongoc_collection_destroy (collection); mongoc_client_destroy (client); mongoc_cleanup (); return EXIT_SUCCESS; }
3
分配连接字符串
将 <connection string>
占位符替换为您从创建连接字符串 步骤中复制的连接字符串。
4
运行您的C应用程序
在您的shell中,运行以下命令以编译和运行此应用程序
gcc -o quickstartc quickstart.c $(pkg-config --libs --cflags libmongoc-1.0) ./quickstartc
命令行输出包含有关检索到的电影文档的详细信息
{ "_id" : { "$oid" : "..." }, "plot" : "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.", ... "title" : "The Shawshank Redemption", ...
如果您遇到错误或没有输出,请确保在 quickstart.c
文件中指定了正确的连接字符串,并且已加载示例数据。
完成这些步骤后,您将拥有一个使用驱动程序连接到您的MongoDB部署、在示例数据上运行查询并打印出结果的工作应用程序。
注意
如果您在此步骤中遇到问题,请在MongoDB社区论坛 中寻求帮助或通过使用此页面的右上角或右下角的评分此页 标签提交反馈。