你能改变一个bsoncxx对象(文档/值/元素)吗?

时间:2016-06-21 09:35:44

标签: c++ json bson

我正在使用 mongocxx 驱动程序,我正在考虑将BSON中给出的查询结果保留为几个对象中的数据持有者,而不是解析BSON以检索值然后丢弃它

这有点意义“ if ”我可以动态编辑BSON。除了构建器之外,我在 bsoncxx 驱动程序文档中找不到任何内容,这些构建器允许我在构造之后操作 bsoncxx 文档/值/视图/元素。

举个例子,假设我有类似的东西

fruit["orange"];

其中fruitbsoncxx::document::element

我可以使用其中一个.get_xxx operators来获取值。

我找不到的东西就像

fruit["orange"] = "ripe";

有没有办法做到这一点,或者构建器背后的想法是“只是”创建一个查询以提供给数据库?

1 个答案:

答案 0 :(得分:0)

有一个相同主题的问题,请参阅here

所以,bsoncxx对象似乎是不可变的,如果我们需要编辑它们,我们必须重新创建它们。:(

我写了一个非常糟糕的解决方案,从头开始重新创建文档

但我想这是一个解决方案。

std::string bsoncxx_string_viewToString(core::v1::string_view gotStringView) {
    std::stringstream convertingStream;
    convertingStream << gotStringView;
    return std::move(convertingStream.str());
}

std::string b_utf8ToString(bsoncxx::types::b_utf8 gotB_utf8) {
    return std::move(bsoncxx_string_viewToString(core::v1::string_view(gotB_utf8)));
}

template <typename T>
bsoncxx::document::value editBsoncxx(bsoncxx::document::view documentToEdit, std::string keyToEdit, T newValue, bool appendValueIfKeyNotExist = true) {
    auto doc = bsoncxx::builder::stream::document{};
    std::string currentKey;
    for (auto i : documentToEdit) {
        currentKey = bsoncxx_string_viewToString(i.key());
        if (currentKey == keyToEdit) {
            doc << keyToEdit << newValue;
            appendValueIfKeyNotExist = false;
        } else {
            doc << currentKey << i.get_value();
        }
    }
    if (appendValueIfKeyNotExist) // Maybe this would be better with documentToEdit.find(key), but I don't know how to check if iterator is past-the-end
        //If there is a way to check if bsoncxx contains key, we can achieve ~o(log(n)) [depending on 'find key' implementation] which is better than o(n)
        doc << keyToEdit << newValue;
    return doc.extract();
}

用法:

auto doc = document{} << "foo0" << "bar0" << "foo1" << 1  << "foo2" << 314 << finalize;
std::cout << bsoncxx::to_json(doc) << std::endl << std::endl;


doc = editBsoncxx<std::string> (doc.view(), "foo1", "edited"); //replace "foo1" with string "edited"
doc = editBsoncxx<int>(doc.view(), "baz_noappend", 123, false); //do nothing if key "baz_noappend" is not found. <- if key-existance algorythm will be applied, we'd spend about o(lob(n)) here, not o(n)
doc = editBsoncxx<int>(doc.view(), "baz_append", 123, true); //key will not be found => it'll be appended which is default behaviour
std::cout << bsoncxx::to_json(doc) << std::endl;

结果:

{ "foo0" : "bar0", "foo1" : 1, "foo2" : 314 } { "foo0" : "bar0", "foo1" : "edited", "foo2" : 314, "baz_append" : 123 }

因此,在您的情况下,您可以使用

fruit = editBsoncxx<std::string>(fruit.view(), "orange", "ripe");

但是,再一次,see already-mentioned related question说出来是对的

  

构建器背后的想法是“只是”创建一个查询以提供给数据库吗?

我认为,解决方案将是“不要编辑文档”。

  

你也可以写类似转换器从bsoncxx到其他json存储fomat(例如,rapidjson)
 小心{value:“valid_json”}:bsoncxx :: to_json不会在值=&gt;中添加反斜杠引号。可以注射。