[bsoncxx]如何将bsoncxx :: document :: element附加到bsoncxx :: builder :: basic :: document?

时间:2017-07-31 10:18:37

标签: c++ mongodb bson mongo-cxx-driver

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

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

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

由于

2 个答案:

答案 0 :(得分: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()));

答案 1 :(得分: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 Reference