mongoc_client_command_simple
来源:互联网 发布:c语言memset头文件 编辑:程序博客网 时间:2024/05/21 13:58
前言
刚开始玩MongoDB
看到mongoc_client_command_simple函数, 不太明白干嘛用的.
看了mongo-c-driver中的代码示例, 大致明白了.
mongoc_client_command_simple等于在mongo本地控制台执行一些mongo自己的数据库命令, 并返回结果.
大致将mongo源码中使用的mongoc_client_command_simple的例子试了一遍, 大概有5,6个例子
使用mongoc_client_command_simpled的API列表
mongoc_collection_command_simple
mongoc_database_command_simple
background_mongoc_client_command_simple
这几个API没有试, 用到的时候, 再试验.
测试程序
#include <stdlib.h>#include <stdio.h>#include <sys/stat.h>#include <cstddef>#include "MongoDbEx.h"int testcase_mongoc_example_command_simple(int argc, char* argv[]);int main(int argc, char* argv[]){ printf("============================================================\n"); printf(">> testcase v1.0.0.3\n"); printf("============================================================\n"); testcase_mongoc_example_command_simple(argc, argv); printf("============================================================\n"); printf("END\n"); printf("============================================================\n"); return 0;}int testcase_mongoc_example_command_simple(int argc, char* argv[]){ mongoc_client_t* client = NULL; mongoc_database_t* database = NULL; mongoc_collection_t* collection = NULL; bson_t* insert = NULL; bson_error_t error; bool retval = false; mongoc_init(); client = mongoc_client_new("mongodb://localhost:27017"); /* * Register the application name so we can track it in the profile logs * on the server. This can also be done from the URI (see other examples). */ mongoc_client_set_appname(client, "connect-example"); database = mongoc_client_get_database(client, "db_name"); collection = mongoc_client_get_collection(client, "db_name", "coll_name"); // cmd : ping retval = DbOptExec_command_simple(client, "admin", "ping", &error); if (!retval) { ShowErrMsg("ping", &error); return EXIT_FAILURE; } /** [ping] { "ok" : 1.0 } */ insert = BCON_NEW("hello", BCON_UTF8("world")); if (!mongoc_collection_insert( collection, MONGOC_INSERT_NONE, insert, NULL, &error)) { ShowErrMsg("mongoc_collection_insert", &error); } // cmd : buildinfo bson_destroy(insert); retval = DbOptExec_command_simple(client, "admin", "buildinfo", &error); if (!retval) { ShowErrMsg("buildinfo", &error); } /** [buildinfo] { "version" : "2.6.10", "gitVersion" : "5901dbfb49d16eaef6f2c2c50fba534d23ac7f6c", "OpenSSLVersion" : "", "sysInfo" : "Linux build18.nj1.10gen.cc 2.6.32-431.3.1.el6.x86_64 #1 SMP Fri Jan 3 21:39:27 UTC 2014 x86_64 BOOST_LIB_VERSION=1_49", "loaderFlags" : "-fPIC -pthread -Wl,-z,now -rdynamic", "compilerFlags" : "-Wnon-virtual-dtor -Woverloaded-virtual -fPIC -fno-strict-aliasing -ggdb -pthread -Wall -Wsign-compare -Wno-unknown-pragmas -Winvalid-pch -pipe -Werror -O3 -Wno-unused-function -Wno-deprecated-declarations -fno-builtin-memcmp", "allocator" : "tcmalloc", "versionArray" : [ 2, 6, 10, 0 ], "javascriptEngine" : "V8", "bits" : 64, "debug" : false, "maxBsonObjectSize" : 16777216, "ok" : 1.0 } */ // cmd : serverStatus retval = DbOptExec_command_simple(client, "admin", "serverStatus", &error); if (!retval) { ShowErrMsg("serverStatus", &error); } /** [serverStatus] { "host" : "debian", "version" : "2.6.10", "process" : "mongod", "pid" : 3243, "uptime" : 21899.0, "uptimeMillis" : 21897854, "uptimeEstimate" : 19920.0, "localTime" : { "$date" : 1491227764737 }, "asserts" : { "regular" : 0, "warning" : 0, "msg" : 0, "user" : 0, "rollovers" : 0 }, "backgroundFlushing" : { "flushes" : 364, "total_ms" : 54, "average_ms" : 0.14835164835164835195, "last_ms" : 0, "last_finished" : { "$date" : 1491227708337 } }, "connections" : { "current" : 1, "available" : 818, "totalCreated" : 9 }, "cursors" : { "note" : "deprecated, use server status metrics", "clientCursors_size" : 0, "totalOpen" : 0, "pinned" : 0, "totalNoTimeout" : 0, "timedOut" : 0 }, "dur" : { "commits" : 29, "journaledMB" : 0.0, "writeToDataFilesMB" : 0.0, "compression" : 0.0, "commitsInWriteLock" : 0, "earlyCommits" : 0, "timeMs" : { "dt" : 3044, "prepLogBuffer" : 0, "writeToJournal" : 0, "writeToDataFiles" : 0, "remapPrivateView" : 0 } }, "extra_info" : { "note" : "fields vary by platform", "heap_usage_bytes" : 62725408, "page_faults" : 98 }, "globalLock" : { "totalTime" : 21897856000, "lockTime" : 5334268, "currentQueue" : { "total" : 0, "readers" : 0, "writers" : 0 }, "activeClients" : { "total" : 0, "readers" : 0, "writers" : 0 } }, "indexCounters" : { "accesses" : 19, "hits" : 19, "misses" : 0, "resets" : 0, "missRatio" : 0.0 }, "locks" : { "." : { "timeLockedMicros" : { "R" : 435761, "W" : 5334268 }, "timeAcquiringMicros" : { "R" : 4899977, "W" : 2994540 } }, "admin" : { "timeLockedMicros" : { "r" : 151982, "w" : 0 }, "timeAcquiringMicros" : { "r" : 369253, "w" : 0 } }, "local" : { "timeLockedMicros" : { "r" : 128739, "w" : 83 }, "timeAcquiringMicros" : { "r" : 54838, "w" : 1 } }, "testdb" : { "timeLockedMicros" : { "r" : 2081468, "w" : 130 }, "timeAcquiringMicros" : { "r" : 19698, "w" : 3 } }, "mongodb" : { "timeLockedMicros" : { "r" : 191151, "w" : 128 }, "timeAcquiringMicros" : { "r" : 30413, "w" : 4 } }, "db_name" : { "timeLockedMicros" : { "r" : 375654, "w" : 908 }, "timeAcquiringMicros" : { "r" : 14419, "w" : 40 } }, "Barca" : { "timeLockedMicros" : { "r" : 158307, "w" : 134 }, "timeAcquiringMicros" : { "r" : 19699, "w" : 3 } }, "dbs" : { "timeLockedMicros" : { "r" : 610389, "w" : 224 }, "timeAcquiringMicros" : { "r" : 17663, "w" : 6 } }, "test1" : { "timeLockedMicros" : { "r" : 829203, "w" : 28 }, "timeAcquiringMicros" : { "r" : 15951, "w" : 2 } }, "yekai" : { "timeLockedMicros" : { "r" : 2065973, "w" : 269 }, "timeAcquiringMicros" : { "r" : 61179, "w" : 4 } }, "tutorial" : { "timeLockedMicros" : { "r" : 1491259, "w" : 157 }, "timeAcquiringMicros" : { "r" : 28555, "w" : 3 } } }, "network" : { "bytesIn" : 5730, "bytesOut" : 13310, "numRequests" : 44 }, "opcounters" : { "insert" : 9, "query" : 3641, "update" : 0, "delete" : 0, "getmore" : 0, "command" : 38 }, "opcountersRepl" : { "insert" : 0, "query" : 0, "update" : 0, "delete" : 0, "getmore" : 0, "command" : 0 }, "recordStats" : { "accessesNotInMemory" : 0, "pageFaultExceptionsThrown" : 0, "Barca" : { "accessesNotInMemory" : 0, "pageFaultExceptionsThrown" : 0 }, "admin" : { "accessesNotInMemory" : 0, "pageFaultExceptionsThrown" : 0 }, "db_name" : { "accessesNotInMemory" : 0, "pageFaultExceptionsThrown" : 0 }, "dbs" : { "accessesNotInMemory" : 0, "pageFaultExceptionsThrown" : 0 }, "local" : { "accessesNotInMemory" : 0, "pageFaultExceptionsThrown" : 0 }, "mongodb" : { "accessesNotInMemory" : 0, "pageFaultExceptionsThrown" : 0 }, "test1" : { "accessesNotInMemory" : 0, "pageFaultExceptionsThrown" : 0 }, "testdb" : { "accessesNotInMemory" : 0, "pageFaultExceptionsThrown" : 0 }, "tutorial" : { "accessesNotInMemory" : 0, "pageFaultExceptionsThrown" : 0 }, "yekai" : { "accessesNotInMemory" : 0, "pageFaultExceptionsThrown" : 0 } }, "writeBacksQueued" : false, "mem" : { "bits" : 64, "resident" : 158, "virtual" : 62683, "supported" : true, "mapped" : 31251, "mappedWithJournal" : 62502 }, "metrics" : { "cursor" : { "timedOut" : 0, "open" : { "noTimeout" : 0, "pinned" : 0, "total" : 0 } }, "document" : { "deleted" : 0, "inserted" : 9, "returned" : 0, "updated" : 0 }, "getLastError" : { "wtime" : { "num" : 0, "totalMillis" : 0 }, "wtimeouts" : 0 }, "operation" : { "fastmod" : 0, "idhack" : 0, "scanAndOrder" : 0 }, "queryExecutor" : { "scanned" : 0, "scannedObjects" : 0 }, "record" : { "moves" : 0 }, "repl" : { "apply" : { "batches" : { "num" : 0, "totalMillis" : 0 }, "ops" : 0 }, "buffer" : { "count" : 0, "maxSizeBytes" : 268435456, "sizeBytes" : 0 }, "network" : { "bytes" : 0, "getmores" : { "num" : 0, "totalMillis" : 0 }, "ops" : 0, "readersCreated" : 0 }, "preload" : { "docs" : { "num" : 0, "totalMillis" : 0 }, "indexes" : { "num" : 0, "totalMillis" : 0 } } }, "storage" : { "freelist" : { "search" : { "bucketExhausted" : 0, "requests" : 8, "scanned" : 16 } } }, "ttl" : { "deletedDocuments" : 0, "passes" : 364 } }, "ok" : 1.0 } */ // cmd : ismaster retval = DbOptExec_command_simple(client, "admin", "ismaster", &error); if (!retval) { ShowErrMsg("ismaster", &error); } /** [ismaster] { "ismaster" : true, "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000, "maxWriteBatchSize" : 1000, "localTime" : { "$date" : 1491230240360 }, "maxWireVersion" : 2, "minWireVersion" : 0, "ok" : 1.0 } */ // cmd : getlasterror retval = DbOptExec_command_simple(client, "admin", "getlasterror", &error); if (!retval) { ShowErrMsg("getlasterror", &error); } /** [getlasterror] { "connectionId" : 11, "n" : 0, "syncMillis" : 0, "writtenTo" : null, "err" : null, "ok" : 1.0 } */ // cmd : foo retval = DbOptExec_command_simple(client, "admin", "foo", &error); if (!retval) { ShowErrMsg("foo", &error); } /** [foo] error : no such cmd: foo */ // cmd : empty // 空命令会报错的// retval = DbOptExec_command_simple(client, "admin", "{}", &error);// // if (!retval) {// ShowErrMsg("{}", &error);// } // cmd : empty retval = DbOptExec_command_simple(client, "admin", "", &error); if (!retval) { ShowErrMsg("", &error); } /** [] error : no such cmd: */ // cmd : db retval = DbOptExec_command_simple(client, "admin", "db", &error); if (!retval) { ShowErrMsg("db", &error); } /** [db] error : no such cmd: db */ /** MongoDB shell version: 2.6.10 connecting to: test > show dbs Barca 0.078GB admin 0.078GB db_name 0.078GB local 0.078GB mongodb 0.078GB test1 0.078GB testdb 0.078GB tutorial 0.078GB yekai 7.950GB > > use test1 switched to db test1 > show collections system.indexes test1 > */ // cmd : "{'drop': '%s'}" retval = DbOptExec_command_simple(client, "admin", "use", "test1", &error); if (!retval) { ShowErrMsg("use test1", &error); } /** [use test1] error : no such cmd: use */ retval = DbOptExec_command_simple(client, "test1", "drop", "test1", &error); if (!retval) { ShowErrMsg("drop test1", &error); } /** [drop] { "ns" : "test1.test1", "nIndexesWas" : 1, "ok" : 1.0 } */ /** mongo console > use test1 switched to db test1 > show collections system.indexes > */ // cmd : getCmdLineOpts retval = DbOptExec_command_simple(client, "admin", "getCmdLineOpts", &error); if (!retval) { ShowErrMsg("getCmdLineOpts", &error); } /** [getCmdLineOpts] { "argv" : [ "\/usr\/local\/mongodb\/bin\/mongod", "--config", "\/usr\/local\/mongodb\/bin\/mongodb.conf" ], "parsed" : { "config" : "\/usr\/local\/mongodb\/bin\/mongodb.conf", "net" : { "http" : { "enabled" : false }, "port" : 27017 }, "processManagement" : { "fork" : true }, "storage" : { "dbPath" : "\/usr\/local\/mongodb\/db" }, "systemLog" : { "destination" : "file", "path" : "\/usr\/local\/mongodb\/logs\/mongodb.log" } }, "ok" : 1.0 } */ mongoc_collection_destroy(collection); mongoc_database_destroy(database); mongoc_client_destroy(client); mongoc_cleanup(); return 0;}
mongo函数的封装
// @file MongoDbEx.h// @brief Mongo database operation#ifndef __MONGODB_EX__#define __MONGODB_EX__#include <bson.h>#include <bcon.h>#include <mongoc.h>#ifndef BOOLtypedef bool BOOL;#define TRUE 1#define FALSE 0#endif // #ifndef BOOLBOOL DbOptInit();BOOL DbOptUnInit();mongoc_client_t* DbOptOpenConect(const char* pConnectUrl);void DbOptCloseConect(mongoc_client_t*& pDbConnect);mongoc_database_t* DbOptOpenDb(mongoc_client_t* pDbConnect, const char* pDbName);void DbOptCloseDb(mongoc_database_t*& pDb);mongoc_collection_t* DbOptOpenTbl(mongoc_database_t* pDb, const char* pTblName);void DbOptCloseTbl(mongoc_collection_t*& pTbl);bool DbOptExec_command_simple(mongoc_client_t* pClient, const char* pcDbName, const char* pcCommand, bson_error_t* pError);bool DbOptExec_command_simple(mongoc_client_t* pClient, const char* pcDbName, const char* pcCommand, const char* pcValue, bson_error_t* pError);void ShowErrMsg(const char* pTip, bson_error_t* error);void ShowReply(const char* pTip, bson_t* reply);bson_t* new_formatv_bson(const char *json, ...);char* single_quotes_to_double (const char* str);#endif // #ifndef __MONGODB_EX__
// @file MongoDbEx.cpp// @brief ...#include "MongoDbEx.h"BOOL DbOptInit(){ mongoc_init();}BOOL DbOptUnInit(){ mongoc_cleanup();}mongoc_client_t* DbOptOpenConect(const char* pConnectUrl){ mongoc_client_t* pDbClient = NULL; if (NULL != pConnectUrl) { pDbClient = mongoc_client_new(pConnectUrl); } return pDbClient;}void DbOptCloseConect(mongoc_client_t*& pDbConnect){ if (NULL != pDbConnect) { mongoc_client_destroy(pDbConnect); pDbConnect = NULL; }}mongoc_database_t* DbOptOpenDb(mongoc_client_t* pDbConnect, const char* pDbName){ mongoc_database_t* pDb = NULL; if (NULL != pDbConnect) { pDb = mongoc_client_get_database(pDbConnect, pDbName); } return pDb;}void DbOptCloseDb(mongoc_database_t*& pDb){ if (NULL != pDb) { mongoc_database_destroy(pDb); pDb = NULL; }}mongoc_collection_t* DbOptOpenTbl(mongoc_database_t* pDb, const char* pTblName){ mongoc_collection_t* pTbl = NULL; pTbl = mongoc_database_get_collection(pDb, pTblName); return pTbl;}void DbOptCloseTbl(mongoc_collection_t*& pTbl){ if (NULL != pTbl) { mongoc_collection_destroy(pTbl); pTbl = NULL; }}bool DbOptExec_command_simple(mongoc_client_t* pClient, const char* pcDbName, const char* pcCommand, bson_error_t* pError){ bool retval = false; bson_t* command = NULL; bson_t reply; do { command = BCON_NEW(pcCommand, BCON_INT32(1)); // mongoc_client_command_simple 作用: 让mongodb执行一些命令, 返回一些结果 retval = mongoc_client_command_simple(pClient, pcDbName, command, NULL, &reply, pError); if (!retval) { break; } else { ShowReply(pcCommand, &reply); } } while (0); bson_destroy(&reply); bson_destroy(command); return retval;}bool DbOptExec_command_simple(mongoc_client_t* pClient, const char* pcDbName, const char* pcCommand, const char* pcValue, bson_error_t* pError){ bool retval = false; bson_t reply; bson_t* doc = NULL; char *sz_cmd = NULL; do { // mongoc_client_command_simple 作用: 让mongodb执行一些命令, 返回一些结果 sz_cmd = bson_strdup_printf ("{'%s': '%s'}", pcCommand, pcValue); doc = new_formatv_bson("%s", sz_cmd); retval = mongoc_client_command_simple(pClient, pcDbName, doc, NULL, &reply, pError); bson_free (sz_cmd); if (!retval) { break; } else { ShowReply(pcCommand, &reply); } } while (0); bson_destroy(&reply); bson_destroy(doc); return retval;}void ShowErrMsg(const char* pTip, bson_error_t* error){ if (NULL != error) { fprintf(stderr, "[%s] error : %s\n\n", (NULL != pTip) ? pTip : "", error->message); }}void ShowReply(const char* pTip, bson_t* reply){ char* str = NULL; if (NULL != reply) { str = bson_as_json(reply, NULL); if (NULL != str) { printf("[%s] %s\n\n", (NULL != pTip) ? pTip : "", str); bson_free(str); } }}bson_t* new_formatv_bson(const char *json, ...){ va_list args; bson_error_t error; char *formatted; char *double_quoted; bson_t *doc; if (json) { va_start (args, json); formatted = bson_strdupv_printf (json, args); va_end (args); double_quoted = single_quotes_to_double (formatted); doc = bson_new_from_json ((const uint8_t *) double_quoted, -1, &error); if (!doc) { fprintf (stderr, "%s\n", error.message); abort (); } bson_free (formatted); bson_free (double_quoted); } else { doc = bson_new (); } return doc;}char* single_quotes_to_double (const char* str){ char *result = bson_strdup (str); char *p; for (p = result; *p; p++) { if (*p == '\'') { *p = '"'; } } return result;}
makefile
# testcase by lostspeed# cmd is : ./Makefileclearrm ./testcaserm ./*.olsg++ -c MongoDbEx.cpp -o myDbOpt.o \ -I/usr/local/mongo_c162_driver/include/libmongoc-1.0 \ -I/usr/local/mongo_c162_driver/include/libbson-1.0 \ -L/usr/local/lib \ -L/usr/local/mongo_c162_driver/lib \ -lpthread \ -lmongoc-1.0 \ -lbson-1.0ls g++ testcase_main.cpp myDbOpt.o -o testcase \ -I/usr/local/mongo_c162_driver/include/libmongoc-1.0 \ -I/usr/local/mongo_c162_driver/include/libbson-1.0 \ -L/usr/local/lib \ -L/usr/local/mongo_c162_driver/lib \ -lpthread \ -lmongoc-1.0 \ -lbson-1.0ls./testcase
0 0
- mongoc_client_command_simple
- Zookeeper集群环境搭建
- 第39级台阶,简单DFS
- 分类算法-贝叶斯网络
- 实验二 BMP2YUV文件转换
- LeetCode Algorithms 292. Nim Game 题解
- mongoc_client_command_simple
- PowerDesigner连接oracle数据库 以及连接数据库时出现的问题
- 随记
- poj 3660
- nbut 1674
- c:求1-1000 以内的所有完数
- 算法提高 最长单词&&单词个数统计&&不同单词个数统计
- 蓝桥杯-8-1因式分解(java)
- servlet的四大作用域对象和jsp的九大内置对象及其四大作用域对象