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);
      return EXIT_FAILURE;
  }
  str = bson_as_json (&reply, NULL);
  printf ("%s\n", str);
  insert = BCON_NEW ("hello", BCON_UTF8 ("world"));//字段为hello,值为world字符串
  if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, insert, 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_client_destroy (client);//释放连接对象
  mongoc_cleanup ();//释放libmongoc驱动
  return 0;
}4. 编译 test.c

# gcc -o test test.c -I/usr/local/include/libmongoc-1.0 -I/usr/local/include/libbson-1.0/ -lmongoc-1.0 -lbson-1.0

# ls
test  test.c


5. 运行test

# ./test
{ "ok" : 1 }

连接MongoDB成功!

更多MongoDB相关教程见以下内容

基于CentOS 6.5操作系统搭建MongoDB服务 http://www.linuxidc.com/Linux/2014-11/108900.htm

MongoDB 的详细介绍请点这里
MongoDB 的下载地址请点这里

猜你喜欢

转载自www.linuxidc.com/Linux/2016-07/133317.htm