一例·C语言连接mongodb并创建文档,插入记录
作者:互联网
上机环境ubuntu20.0.4 QtCreator
准备活动,安装libmongoc 和libbson
最好sudo apt 安装 mongodb,这样我们就能获得 mongoc.h
别忘了,在QtCreator选择根目录,右键点击Add Library添加libmongoc.so和libbson.so库函数
#include <stdio.h> #include <bson/bson.h> #include <mongoc/mongoc.h> int main() { mongoc_client_t *client; mongoc_collection_t *collection; bson_error_t error; bson_oid_t oid; bson_t *doc; mongoc_init(); client = mongoc_client_new ("mongodb://192.168.34.128:27017"); collection = mongoc_client_get_collection (client, "ourworld", "mywish"); doc = bson_new (); bson_oid_init (&oid, NULL); BSON_APPEND_OID (doc, "_id", &oid); const char* mykey = "description"; const char* myval ="超级喜欢付高峰"; bson_append_symbol (doc, mykey,strlen(mykey), myval,strlen(myval));//添加键值对集合 BSON_APPEND_UTF8 (doc, "hello","world");//另一种添加键值对的方法,key值是hello,val值是world if (!mongoc_collection_insert_one ( collection, doc, NULL, NULL, &error)) { fprintf (stderr, "%s\n", error.message); } bson_destroy (doc); mongoc_collection_destroy (collection); mongoc_client_destroy (client); mongoc_cleanup (); printf("Hello World!\n"); return 0; }
截止2020年11月,mongodb官方提供了C语言操作mongodb的相关教程,其地址位于 http://mongoc.org/libmongoc/current/index.html
其思路大概是mongo_client_t用于维护与mongodb的连接,mongo_collection_t是和集合相关的操作,bson文档是集合里的每一条记录
所有操作完成后,依次释放bson文档,释放集合mongo_collection,释放mongo_client
标签:mongoc,mongodb,collection,C语言,183,client,doc,bson 来源: https://www.cnblogs.com/saintdingspage/p/14003181.html