现在mongodb 越来越流行,越来越多的公司在使用mongodb数据库。而且为很多语言留下了接口。
个人还是比较喜欢用C去操作各类流行的产品。
准备文件
首先要安装mongodb,mongodb是免安装的,下载解压之后,可以直接启动起来,然后再执行下面的操作.
从https://github.com/mongodb/mongo-c-driver下载
下载后的文件
参考文献:
http://api.mongodb.org/c/current/tutorial.html#c-api
main.c文件
- #include <stdio.h>
- #include "mongo.h"
- int main(){
- mongo conn[1];
- int status = mongo_connect(conn,"127.0.0.1",27017);
- if( status != MONGO_OK ) {
- switch ( conn->err ) {
- case MONGO_CONN_SUCCESS: printf( "connection succeeded\n" ); break;
- case MONGO_CONN_NO_SOCKET: printf( "no socket\n" ); return 1;
- case MONGO_CONN_FAIL: printf( "connection failed\n" ); return 1;
- case MONGO_CONN_NOT_MASTER: printf( "not master\n" ); return 1;
- }
- }
- char *table="test.people";
- // Create Json Data
- bson b[1];
- bson_init(b);
- bson_append_string(b,"name","joe");
- bson_append_int(b, "age", 33);
- bson_finish(b);
- mongo_insert(conn, table, b);
- // Query the Data
- mongo_cursor cursor[1];
- mongo_cursor_init(cursor, conn, table);
- while(mongo_cursor_next(cursor) == MONGO_OK){
- bson_print(&cursor->current);
- }
- bson_destroy(b);
- mongo_destroy(conn);
- return 0;
- }
Makefile
- CC=gcc
- 1:
- ${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
编译
- [www@zhoubc c]$ make
- 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
执行
- [www@zhoubc c]$ ./main
- _id : 7 4e5718002cec9da3a541f387
- name : 2 joe
- age : 16 33
- _id : 7 4e5718402cec9da3a541f388
- name : 2 joe
- age : 16 33
- _id : 7 4e57184a2cec9da3a541f389
- name : 2 joe
- age : 16 33
- _id : 7 4e5719a62cec9da3a541f38a
- name : 2 joe
- age : 16 33
转自:http://rtxbc.iteye.com/blog/1158630