Mongo - 从值获取view_or_value?

时间:2017-07-18 15:17:40

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

我刚刚开始使用Mongo,而我在将文档写入集合时遇到了一些麻烦。我似乎无法将document :: value转换为string :: view_or_value。有关整理这些类型的任何提示?我尝试直接发送doc_value,但这对插入文件无效。

#include "stdafx.h"
#include <cstdint>
#include <iostream>
#include <vector>
#include <mongocxx/instance.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>

using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::open_document;

int main()
{
    mongocxx::instance instance{};
    mongocxx::client client{ mongocxx::uri{} };
    mongocxx::database db = client["mydb"];
    bsoncxx::builder::stream::document builder{};
    bsoncxx::document::value doc_value = builder
        << "name" << "MongoDB"
        << "type" << "database"
        << "count" << 1
        << "versions" << bsoncxx::builder::stream::open_array
        << "v3.2" << "v3.0" << "v2.6"
        << close_array
        << "info" << bsoncxx::builder::stream::open_document
        << "x" << 203
        << "y" << 102
        << bsoncxx::builder::stream::close_document
        << bsoncxx::builder::stream::finalize;

    db.collection("cats").insert_one(bsoncxx::string::view_or_value(doc_value));
    return 0;
}

1 个答案:

答案 0 :(得分:1)

mongocxx::collection::insert_one需要bsoncxx::document::view_or_value,而不是bsoncxx::string::view_or_value。我希望以下内容能够正常运作:

db.collection("cats").insert_one(std::move(doc_value));

请注意,这会将文档作为值传输。如果您只想传递视图:

db.collection("cats").insert_one(doc_value.view());

不会转让所有权。