一、搭建
搭建参考:http://mongoc.org/libmongoc/current/installing.html
二、使用
1、引入mongo c driver
动态静态库的系统路径是:/usr/local/lib64
头文件路径:/usr/lib/include
cmake文件如下:
2、链接数据库
mongoc_client_t *client = NULL;
mongoc_collection_t *collection = NULL;
// 初始化libmongoc
mongoc_init ();
// 连接到数据库,并获取集合句柄
client = mongoc_client_new ("mongodb://192.168.1.191:27017/");
collection = mongoc_client_get_collection (client, "cvedb", "importcve");
3、插入
void insert(mongoc_collection_t *collection){
bson_error_t error;
bson_oid_t oid;
bson_t *doc;
bson_t child;
// 创建一个bson文档,并追加键值对数据
doc = bson_new ();
bson_oid_init (&oid, NULL);
BSON_APPEND_OID (doc, "_id", &oid);
BSON_APPEND_UTF8 (doc, "name", "yangjing");
BSON_APPEND_UTF8 (doc, "id", "1");
BSON_APPEND_DOCUMENT_BEGIN(doc,"fullname",&child);
BSON_APPEND_UTF8 (&child, "firstname", "jing");
BSON_APPEND_UTF8 (&child, "lastname", "yang");
bson_append_document_end(doc,&child);
// 将bson文档插入到集合
if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
}
// 释放资源
bson_destroy (doc);
}
4、更新
void updata(mongoc_collection_t *collection){
bson_error_t error;
bson_t *update = NULL;
bson_t *query = NULL;
query = bson_new();
BSON_APPEND_UTF8 (query, "name", "yinjing");
update = BCON_NEW