2017-07-18 1 views
1

私はちょうどMongoを使い始めています。コレクションに文書を書くのに手間取っています。私はdocument :: valueを文字列:: view_or_valueに変換することはできません。これらのタイプを整理する際のヒント?私はdoc_valueを直接送信しようとしましたが、それは挿入のためには有効ではありません。Mongo - 値からview_or_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

mongocxx::collection::insert_onebsoncxx::string::view_or_valueない、bsoncxx::document::view_or_valueをとります。私は次のことだけがうまくいくと期待しています:

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

文書は値として転送されることに注意してください。表示を渡すだけの場合:

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

これは所有権を譲渡しません。

+0

AHA!それがそれでした。 bsoncxxで直感を立てるための推奨読書はありますか? – Carbon

+1

かなり広範なサンプルと単体テストがあり、ここにかなりの量のドキュメンテーションがあります:https://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/working-with-bson/ – acm

関連する問題