我正在使用Mongo C API为项目实现数据库接口。
MongoDB文件:
{
_id,
... // Some fields
...
Array
}
用于填充数组中值的查询:
BCON_APPEND (&query, "$push", "{",
"Array", "{",
"Key", key,
"Value", (char*)value, "}",
"}");
MongoDB中的填充数组:
"Array" : [ { "Key": "key1", "Value" : "string1" },
{ "Key": "key2", "Value" : "string2" },
{ "Key": "key3", "Value" : "string3" },
]
用于查找数组中匹配行的查询:
BCON_APPEND (&query, $elemMatch,
"Array", "{", "Key", key,
"}");
此查询返回包含数组中匹配键的完整文档 - 这很好。
问题:
我正在阅读此查询返回的文档的每个字段 - 逐个。
当我在文档中遇到Array字段时 - 我的要求是只获得匹配的行。
我尝试按如下方式读取数组:
uint32_t *document_len;
const uint8_t **document;
bson_iter_recurse (&iter, &sub_iter))
{
while (bson_iter_next (&sub_iter))
{
bson_iter_document (sub_iter,
&document_len,
document)
// Suppose my "Key" was: "key2"
// How to get the matching row: { "Key": "key2", "Value" : "string2" } as a String here ?
// Also, I want to receive ONLY matching row -- & NOT all 3 rows
}
}
我无法从此数组中读取字符串,也无法仅获取匹配的行 - 而不是所有3行。
[注意:在上面的while()循环中,如果我把这个跟踪:
while (bson_iter_next (&sub_iter))
{
printf ("Found key \"%s\" in sub document.\n",
bson_iter_key (&sub_iter));
}
我得到3张照片:
Found key 0 in sub document
Found key 1 in sub document
Found key 2 in sub document
所以,很明显 - 我从数组中获取所有值,而不是唯一匹配的值,我无法从数组中检索实际的字符串]
参考文献:
Mongo C API https://api.mongodb.org/c/current/
libbson https://api.mongodb.org/libbson/current/bson_iter_t.html
请帮忙。