これが私のコレクションの構造部分です:
{
...
list: [
{ id:'00A', name:'None 1' },
{ id:'00B', name:'None 2' },
],
...
}
C libで「id」および/または「name」フィールドの値のリストを取得するには、どの方法をアドバイスしてもらえますか?
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);
}
上記の例では、データベースは「foo」であり、類似のドキュメントを含むコレクションは「test」です。上記のクエリ部分は次と同等です。
db.runCommand({distinct:'foo', key:'list.id'})
それが役立つことを願っています。
ジェイク