bsoncxx::stdx::optional<result::insert_one> collection::insert_one(bsoncxx::document::view document,
                                                                   const options::insert& options) {
    class bulk_write bulk_op(false);
    bsoncxx::document::element oid{};

    bsoncxx::builder::stream::document new_document;
    if (!document["_id"]) {
        new_document << "_id" << bsoncxx::oid(bsoncxx::oid::init_tag);
        new_document << bsoncxx::builder::stream::concatenate{document};
        bulk_op.append(model::insert_one(new_document.view()));
        oid = new_document.view()["_id"];
    } else {
        bulk_op.append(model::insert_one(document));
        oid = document["_id"];
    }

    if (options.write_concern()) {
        bulk_op.write_concern(*options.write_concern());
    }

    auto result = bulk_write(bulk_op);
    if (!result) {
        return bsoncxx::stdx::optional<result::insert_one>();
    }

    return bsoncxx::stdx::optional<result::insert_one>(
        result::insert_one(std::move(result.value()), std::move(oid.get_value())));
}
示例#2
0
stdx::optional<result::insert_one> collection::insert_one(view_or_value document,
                                                          const options::insert& options) {
    // TODO: We should consider making it possible to convert from an options::insert into
    // an options::bulk_write at the type level, removing the need to re-iterate this code
    // many times here and below.
    //
    // See comments in: https://github.com/mongodb/mongo-cxx-driver/pull/409

    options::bulk_write bulk_opts;
    bulk_opts.ordered(false);

    if (options.write_concern()) {
        bulk_opts.write_concern(*options.write_concern());
    }

    if (options.bypass_document_validation()) {
        bulk_opts.bypass_document_validation(*options.bypass_document_validation());
    }

    class bulk_write bulk_op(bulk_opts);
    bsoncxx::document::element oid{};

    bsoncxx::builder::basic::document new_document;
    if (!document.view()["_id"]) {
        new_document.append(kvp("_id", bsoncxx::oid()));
        new_document.append(concatenate(document));
        bulk_op.append(model::insert_one(new_document.view()));
        oid = new_document.view()["_id"];
    } else {
        bulk_op.append(model::insert_one(document));
        oid = document.view()["_id"];
    }

    auto result = bulk_write(bulk_op);
    if (!result) {
        return stdx::nullopt;
    }

    return stdx::optional<result::insert_one>(
        result::insert_one(std::move(result.value()), std::move(oid.get_value())));
}