mongodb-C中子数组中的子对象

Joh*_*n S 0 mongodb bson mongodb-c

这是我的集合的结构部分:

{
   ...
   list: [
      { id:'00A', name:'None 1' },
      { id:'00B', name:'None 2' },
   ],
   ...
}
Run Code Online (Sandbox Code Playgroud)

您可以建议我使用C lib检索"id"和/或"name"字段中的值列表,请使用哪种方法?

小智 7

看来你要求用C驱动程序等效"db.collection.distinct".那是对的吗?如果是这样,您可以使用mongo_run_command函数发出distinct作为db命令:

http://api.mongodb.org/c/current/api/mongo_8h.html#a155e3de9c71f02600482f10a5805d70d

以下是您可能会发现的一段有用的代码,用于演示实现:

mongo conn[1];
int status = mongo_client(conn, "127.0.0.1", 27017);

if (status != MONGO_OK)
    return 1;

bson b[1]; // query bson
bson_init(b);
bson_append_string(b, "distinct", "foo");
bson_append_string(b, "key", "list.id"); // or list.name
bson_finish(b);

bson bres[1]; // result bson

status = mongo_run_command(conn, "test", b, bres);

if (status == MONGO_OK){
    bson_iterator i[1], sub[1];
    bson_type type;
    const char* val;

    bson_find(i, bres, "values");
    bson_iterator_subiterator(i, sub);

    while ((type = bson_iterator_next(sub))) {
        if (type == BSON_STRING) {
            val = bson_iterator_string(sub);
            printf("Value: %s\n", val);
        }
    }
} else {
    printf("error: %i\n", status);
}
Run Code Online (Sandbox Code Playgroud)

数据库是"foo",包含类似于你的文档的集合在上面的例子中是"test".上述查询部分相当于:

db.runCommand({distinct:'foo', key:'list.id'})
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.

可靠的人