查询不同的值并迭代结果MongoDB C API

时间:2013-05-11 09:46:44

标签: 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

感谢任何帮助

1 个答案:

答案 0 :(得分:0)

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

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附带的样本确实有效:)