[bsoncxx ]如何附加一个bsoncxx::d ocument::element TO bsoncxx::buil



尝试将元素附加到文档时出错。

bsoncxx::document::value _obj;  //This is Declaration of _obj in diffrent file
bsoncxx::document::element element = _obj.view()[sFieldName];
if (element.length() && element.type() == bsoncxx::type::k_document)
{
bsoncxx::builder::basic::document bsonBuilder;
bsonBuilder.append(element); //Getting Error
}
错误: 错误 C2664 'void bsoncxx::v_noabi::builder:::basic::sub_document::

append_(bsoncxx::v_noabi::builder::concatenate_doc(': 无法从"bsoncxx::v_noabi::d ocument::元素"转换参数 1 到 'bsoncxx::v_noabi::builder::concatenate_doc'

请帮我解决这个问题,如何将元素转换为文档或将元素附加到文档。

谢谢

要将元素附加到构建器,您需要使用bsoncxx::builder::basic::kvp并分别从元素传入键和值:

using bsoncxx::builder::basic::kvp;
bsoncxx::document::element elem = ...;
bsoncxx::builder::basic::document builder;
builder.append(kvp(elem.key(), elem.get_value()));

我认为您正在尝试创建此JSON结构:

{
"key1": "value1",
"key2":
{   //this is your sub-document...
"subkey1": "subvalue1",
"subkey2": "subvalue2"
}
}

如果我将此结构与您的代码进行比较,您将缺少key2.尝试使用帮助程序函数kvp()(键值对(。


附上一个小示例,以使用多边形创建地理空间查询。

using bsoncxx::builder::basic::sub_document;
using bsoncxx::builder::basic::sub_array;
using bsoncxx::builder::basic::kvp;
bsoncxx::builder::basic::document doc{};
doc.append(kvp("info.location",[a_polygon](sub_document subdoc) {
subdoc.append(kvp("$geoWithin", [a_polygon](sub_document subdoc2)
{
subdoc2.append(kvp("$geometry", [a_polygon](sub_document subdoc3)
{
subdoc3.append(kvp("type","Polygon"));
subdoc3.append(kvp("coordinates",[a_polygon](sub_array subarray)
{
subarray.append([a_polygon](sub_array subarray2)        
{
for (auto point : a_polygon->points())
{
subarray2.append([point](sub_array coordArray)
{
coordArray.append(point.longitude(), point.latitude());
});
}
});
}));
}));        
}));
}));

查询结构:

{
<location field>: {
$geoWithin: {
$geometry: {
type: <"Polygon" or "MultiPolygon"> ,
coordinates: [ <coordinates> ]
}
}
}
}

来源:MongoDB Reference

最新更新