Linux平台下MongoDB的C语言编程实例

【广告位】文章头部(标题下方、正文上方)

下面讲述在Linux平台下MongoDB的C语言编程实例

假设已经安装好了MongoDB。

1. 下载MongoDB的C语言驱动并安装

这里下载的MongoDB的C语言驱动是 mongo-c-driver-1.3.5.tar.gz。

解压后打开mongo-c-driver-1.3.5目录下的 README 文件,按其中讲的方法安装,如下:

  # tar xzf mongo-c-driver-1.3.5.tar.gz
  # cd mongo-c-driver-1.3.5
  # ./configure
  # make
  # sudo make install

2. 启动MongoDB

# mongod
2016-07-10T11:53:20.075+0800 I CONTROL  [initandlisten] MongoDB starting : pid=3071 port=27017 dbpath=/data/db 64-bit host=localhost.localdomain
2016-07-10T11:53:20.076+0800 I CONTROL  [initandlisten] db version v3.2.7
2016-07-10T11:53:20.076+0800 I CONTROL  [initandlisten] git version: 4249c1d2b5999ebbf1fdf3bc0e0e3b3ff5c0aaf2
...

3. 编写连接MongoDB的程序 test.c

#include <bson.h>
#include <bcon.h>
#include <mongoc.h>
int
main (int  argc,
      char *argv[])
{
  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 ();//初始化libmongoc驱动
  /*
    * Create a new client instance
    */
  client = mongoc_client_new ("mongodb://localhost:27017");//创建连接对象
  /*
    * 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);

【广告位】文章正文中间
本文已展示 50% · 完整内容需验证码解锁

关注公众号,解锁完整文章

微信扫码关注 星哥玩云, 在公众号对话框回复关键词 星哥玩云博客 获取验证码。输入后即可阅读全文, 一次解锁全站文章通用。

星哥玩云 微信公众号二维码
微信扫一扫 / 长按识别,关注「星哥玩云」
【广告位】文章底部(正文结束、评论区上方)
评论功能已在静态化后停用 · 返回顶部 ↑