mongodb-C中子数组中的子对象 [英] sub-object in sub-array in mongodb-C

查看:98
本文介绍了mongodb-C中子数组中的子对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我收藏的结构部分:

Here's the structure part of my collection :

{
   ...
   list: [
      { id:'00A', name:'None 1' },
      { id:'00B', name:'None 2' },
   ],
   ...
}

您可以建议采用哪种方法来检索 id和/或带有C lib的名称字段,请问?

Which method could you advise me to retrieve the list of values in the "id" and/or "name" field with C lib please ?

推荐答案

似乎您要的是等价于 db .collection.distinct与C驱动程序。那是对的吗?如果是这样,则可以使用mongo_run_command函数将db命令作为db命令发出:

It seems you are asking for the equivalent of "db.collection.distinct" with the C driver. Is that correct? If so, you can issue distinct as a db command using the mongo_run_command function:

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

以下是演示实现的有用代码:

Here is a piece of code you may find useful demonstrating the implementation:

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);
}

数据库为 foo,集合中包含与您相似的文档,在上面的示例中为测试。上面的查询部分等效于:

The database is "foo" and the collection, containing documents similar to yours, is "test" in the above example. The query portion of the above is equivalent to:

db.runCommand({distinct:'foo', key:'list.id'})

希望有帮助。

杰克

这篇关于mongodb-C中子数组中的子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆