Mongodb 的C语言操作

来源:互联网 发布:yy官方协议软件 编辑:程序博客网 时间:2024/05/01 22:49

现在mongodb 越来越流行,越来越多的公司在使用mongodb数据库。而且为很多语言留下了接口。

个人还是比较喜欢用C去操作各类流行的产品。

 

准备文件

首先要安装mongodb,mongodb是免安装的,下载解压之后,可以直接启动起来,然后再执行下面的操作.

 

 

从https://github.com/mongodb/mongo-c-driver下载

 

 

下载后的文件

 

 

参考文献:

http://api.mongodb.org/c/current/tutorial.html#c-api

 

 

main.c文件

 

C代码  收藏代码
  1. #include <stdio.h>  
  2. #include "mongo.h"  
  3.   
  4. int main(){  
  5.     mongo conn[1];  
  6.     int status = mongo_connect(conn,"127.0.0.1",27017);  
  7.     if( status != MONGO_OK ) {   
  8.         switch ( conn->err ) {   
  9.             case MONGO_CONN_SUCCESS:    printf( "connection succeeded\n" ); break;  
  10.             case MONGO_CONN_NO_SOCKET:  printf( "no socket\n" ); return 1;  
  11.             case MONGO_CONN_FAIL:       printf( "connection failed\n" ); return 1;  
  12.             case MONGO_CONN_NOT_MASTER: printf( "not master\n" ); return 1;  
  13.         }     
  14.     }     
  15.   
  16.     char *table="test.people";  
  17.   
  18.     // Create Json Data  
  19.     bson b[1];  
  20.     bson_init(b);  
  21.     bson_append_string(b,"name","joe");  
  22.     bson_append_int(b, "age", 33);  
  23.     bson_finish(b);  
  24.     mongo_insert(conn, table, b);   
  25.   
  26.   
  27.     // Query the Data  
  28.     mongo_cursor cursor[1];  
  29.     mongo_cursor_init(cursor, conn, table);  
  30.     while(mongo_cursor_next(cursor) == MONGO_OK){  
  31.         bson_print(&cursor->current);  
  32.     }     
  33.                                  
  34.     bson_destroy(b);  
  35.     mongo_destroy(conn);  
  36.   
  37.     return 0;  
  38. }  
 

Makefile

Sh代码  收藏代码
  1. CC=gcc  
  2.   
  3. 1:  
  4.     ${CC} -Isrc --std=c99 /home/share/db/driver/mongo-driver-c/src/*.c -I/home/share/db/driver/mongo-driver-c/src/ main.c -o main  
 

编译

Sh代码  收藏代码
  1. [www@zhoubc c]$ make  
  2. gcc -Isrc --std=c99 /home/share/db/driver/mongo-driver-c/src/*.c -I/home/share/db/driver/mongo-driver-c/src/ main.c -o main  

 

执行

Sh代码  收藏代码
  1. [www@zhoubc c]$ ./main   
  2.     _id : 7      4e5718002cec9da3a541f387  
  3.     name : 2     joe  
  4.     age : 16     33  
  5.     _id : 7      4e5718402cec9da3a541f388  
  6.     name : 2     joe  
  7.     age : 16     33  
  8.     _id : 7      4e57184a2cec9da3a541f389  
  9.     name : 2     joe  
  10.     age : 16     33  
  11.     _id : 7      4e5719a62cec9da3a541f38a  
  12.     name : 2     joe  
  13.     age : 16     33  
  • 大小: 7.2 KB
  • 大小: 92.3 KB
转自:http://rtxbc.iteye.com/blog/1158630
0 0
原创粉丝点击