Search code examples
c++mongodbmongo-cxx-driver

Mongo - get a view_or_value from a value?


I'm just getting started with Mongo, and I'm having some trouble getting it to write a document to a collection. I can't seem to convert from a document::value to a string::view_or_value. Any hints on sorting out these types? I tried sending the doc_value directly, but that's not valid for the insert one.

#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;
}

Solution

  • mongocxx::collection::insert_one takes a bsoncxx::document::view_or_value, not a bsoncxx::string::view_or_value. I would expect the following to just work:

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

    Note that that will transfer the document as a value. If you just want to pass a view:

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

    Which will not transfer ownership.