c - 查询不同的值并遍历结果 MongoDB C API

标签 c api mongodb

我正在尝试运行一个仅从 MongoDB 获取不同值的查询。我运行了查询并返回了正确的值,但是我不确定如何使用 C API 迭代生成的 BSON 数组。

代码如下:

bson query;
bson out;

bson_init(&query);
bson_append_string(&query, "distinct", "myCollection");
bson_append_string(&query, "key", "someKey");
bson_finish(&query);

if (mongo_run_command( conn, "myDB", &query, &out ) != MONGO_OK) {
   printf("mongo_run_command failed!\n");
   return 1;
}
else {
while(bson_iterator_next(out)){
   bson iterator;
   if (bson_find(iterator, &out, "someKey")) {
      printf("%s\n", bson_iterator_string(iterator));
   }
}
bson_print(&out);

bson_print(&out) 确实打印出正确的数组,但我如何遍历该数组?

C API 的文档非常薄,甚至没有涵盖 mongo_run_command

感谢任何帮助

最佳答案

我解决了。对于那些正在寻找解决方案的人来说,这里对我有用:

bson outSub[1];
bson_iterator iterator[1];
bson_iterator iterator2[1];
bson_type type;
const char *value;

// advance to the values array
bson_find(iterator, out, "values");
bson_iterator_subobject_init(iterator, outSub, 0);

bson_iterator_init(iterator2, outSub );
while (bson_iterator_more(iterator2)) {
   type = bson_iterator_next(iterator2);
   value = bson_iterator_string(iterator2);
   if (strlen(value) > 0) {
      printf( "Value: %s\n", value);
   }
}
bson_destroy(outSub);

检查 C API 附带的示例确实值得:)

关于c - 查询不同的值并遍历结果 MongoDB C API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16495811/

相关文章:

node.js - 在 NodeJS 中获取和发布文本

javascript - 如何将来 self 正在使用的 API 的 JSON 响应分配给页面上的元素?

c - 为什么 gcc 接受 "int a = 3i;"作为有效语句?

iphone - Objective-C/iOS - 测试是否存在 C 函数?

javascript - 在 AngularJS 中使用 ng-repeat 的 API JSON 响应

node.js - 如何获取 mongodb 中不同元素的最大值?

node.js - 分别获取 MongoDB 集合后加入它们

mongodb - 如何计算mongodb spring中特定字段的平均值?

c++ - 显式链接的 DLL 中的 CDecl 清理代码

c - 错误 : expected expression before 'unsigned'