代码之家  ›  专栏  ›  技术社区  ›  Carbon

Mongo-从值中获取view\u或_值?

  •  1
  • Carbon  · 技术社区  · 7 年前

    #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 回复  |  直到 7 年前
        1
  •  1
  •   acm    7 年前

    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());
    

    不会转让所有权。