다음 코드를 실행하면 설정한 db의 collection에 hello:world(키:값) 을 추가 해준다.
#include <stdio.h>
#include <bson.h>
#include <bcon.h>
#include <mongoc.h>
int main (int argc,char *argv[]){
mongoc_client_t *client; // DB주소를 담을 변수
mongoc_database_t *database; // DB이름을 담을 변수
mongoc_collection_t *collection; // collection 이름을 담을 변수
bson_t *command, // mongodb에서 사용할 명령어
reply,
*insert;
bson_error_t error;
char *str;
bool retval;
mongoc_init (); // mongoc 시작(제일 먼저 실행되어야함)
client = mongoc_client_new ("mongodb://localhost:27017");
database = mongoc_client_get_database (client, "attendance");// attendance는 db이름
collection = mongoc_client_get_collection (client, "attendance", "userlist"); // userlist는 collection이름
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"));
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);
mongoc_collection_destroy (collection); //collection 삭제
mongoc_database_destroy (database); // database 삭제
mongoc_client_destroy (client); // client 삭제
mongoc_cleanup ();
return 0;
}
출처: http://mongoc.org/libmongoc/1.6.0/index.html
* qt의 경우
INCLUDEPATH += /usr/local/include/libbson-1.0
INCLUDEPATH += /usr/local/include/libmongoc-1.0
LIBS += -lmongoc-1.0
LIBS += -lbson-1.0 를 추가해주자.
*gcc의 경우