1

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

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::document: 转换参数 1: :element' 到 'bsoncxx::v_noabi::builder::concatenate_doc'

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

谢谢

4

2 回答 2

3

要将元素附加到构建器,您需要分别使用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()));
于 2017-08-01T19:35:47.267 回答
2

我认为您正在尝试创建此 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 参考

于 2017-07-31T12:40:02.313 回答