mongodb&c++ Development (iv) Bsoncxx::builder::stream::d ocument of additions and deletions to check operation __c++

Source: Internet
Author: User
2. Mongocxx


And then look at what's in the Mongocxx file.

First look at the basic additions and deletions to check operations: 2.1 connect.cpp Database links



See the previous blog. 2.2 Create.cpp constructs the document and inserts



Constructs a document that inserts a collection in the database. About Builder::stream: The use of:d ocument see the same series of blogs (iii).


#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/types.hpp>

#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>

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

int main(int, char**) {
    mongocxx::instance inst{};
    mongocxx::client conn{mongocxx::uri{}};

    auto db = conn["test"];

    // TODO: fix dates

    // @begin: cpp-insert-a-document
    bsoncxx::document::value restaurant_doc =
        document{} << "address" << open_document << "street"
                   << "2 Avenue"
                   << "zipcode"
                   << "10075"
                   << "building"
                   << "1480"
                   << "coord" << open_array << -73.9557413 << 40.7720266 << close_array
                   << close_document << "borough"
                   << "Manhattan"
                   << "cuisine"
                   << "Italian"
                   << "grades" << open_array << open_document << "date"
                   << bsoncxx::types::b_date{std::chrono::milliseconds{12323}} << "grade"
                   << "A"
                   << "score" << 11 << close_document << open_document << "date"
                   << bsoncxx::types::b_date{std::chrono::milliseconds{121212}} << "grade"
                   << "B"
                   << "score" << 17 << close_document << close_array << "name"
                   << "Vella"
                   << "restaurant_id"
                   << "41704620" << finalize;

    // We choose to move in our document here, which transfers ownership to insert_one()
    auto res = db["restaurants"].insert_one(std::move(restaurant_doc));
    // @end: cpp-insert-a-document
}


Insert a file Restaurant_doc in the restaurant Table (collection) in the database test:


{"Address
     ": {"Street
                     "   : "2 Avenue",
                     "ZipCode"  : "10075",
                     "building": "1480", 
                     "Coord"    : [ -73.9557413,40.7720266],
                 },
    "borough": "Manhattan",
    "cuisine": "Italian",
    "grades"  : [ 
                   {
                       "date"  : * * * time,
                       "grade": "A",
                       "score": one
                   }
                   {
                       "date"  : * * * Time,
                       "grade": "B",
                       "score": "
                   {}
               ]
    " "Name"          : "Vella",
    "restaruant_id": "41706420"
}
2.3 update.cppFind a qualifying document, modify/Create a new key value pair nested modify/Create a key value pair to modify key values in multiple files find a qualifying document, replace part of the document
int main (int, char **) {
    mongocxx :: instance inst {};
    mongocxx :: client conn {mongocxx :: uri {}};

    auto db = conn ["test"];

    // Update top-level fields in a single document.
    {
        // @begin: cpp-update-top-level-fields
        // Find documents with "name": "Juni" key-value pairs, use \ $ set to specify one
        // key "cuisine" (if not created in the document), change the key-value pair
        // Become "cuisine": "American (New)", then use \ $ currentDate to specify
        // Key called "lastModified", bool value true means that the value corresponding to this key is used
        // The form of Date (see commonly used data types in this series (2)
        // Use Unix time format to record the current time.
        bsoncxx :: builder :: stream :: document filter_builder, update_builder;
        filter_builder << "name"
                       << "Juni";
        update_builder << "$ set" << open_document << "cuisine"
                       << "American (New)" << close_document << "$ currentDate" << open_document
                       << "lastModified" << true << close_document;

        db ["restaurants"]. update_one (filter_builder.view (), update_builder.view ());
        // @end: cpp-update-top-level-fields
    }

    // Update an embedded document in a single document.
    // Find information about this restaurant with restaurant_id 41156888, and change the street in the address information (document) to East 31st Street
    {
        // @begin: cpp-update-embedded-field
        bsoncxx :: builder :: stream :: document filter_builder, update_builder;
        filter_builder << "restaurant_id"
                       << "41156888";
        update_builder << "$ set" << open_document << "address.street"
                       << "East 31st Street" << close_document;

        db ["restaurants"]. update_one (filter_builder.view (), update_builder.view ());
        // @end: cpp-update-embedded-field
    }

    // Update multiple documents.
    {
        // @begin: cpp-update-multiple-documents
        bsoncxx :: builder :: stream :: document filter_builder, update_builder;
        filter_builder << "address.zipcode"
                       << "10016"
                       << "cuisine"
                       << "Other";
        update_builder << "$ set" << open_document << "cuisine"
                       << "Category To Be Determined" << close_document << "$ currentDate"
                       << open_document << "lastModified" << true << close_document;

        db ["restaurants"]. update_many (filter_builder.view (), update_builder.view ());
        // @end: cpp-update-multiple-documents
    }

    // Replace the contents of a single document.
    {
        // @begin: cpp-replace-document
        // Find the document containing filter_builder information and replace the corresponding information with
        // replace_builder's information
        bsoncxx :: builder :: stream :: document filter_builder, replace_builder;
        filter_builder << "restaurant_id"
                       << "41704620";
        replace_builder << "name"
                        << "Vella 2"
                        << "address" << open_document << "coord" << open_array << -73.9557413
                        << 40.7720266 << close_array << "building"
                        << "1480"
                        << "street"
                        << "2 Avenue"
                        << "zipcode"
                        << "10075" << close_document;

        db ["restaurants"]. replace_one (filter_builder.view (), replace_builder.view ());
        // @end: cpp-replace-document
    }
}
2.4 Remove.cpp:Delete all document deletion collection in one or more collection document deletion collection
int main (int, char **) {
    mongocxx :: instance inst {};
    mongocxx :: client conn {mongocxx :: uri {}};

    auto db = conn ["test"];

    // Remove all documents that match a condition.
    {
        // @begin: cpp-remove-matching-documents
        // Delete documents with "borough": "Manhattan" key-value pairs
        bsoncxx :: builder :: stream :: document filter_builder;
        filter_builder << "borough"
                       << "Manhattan";

        db ["restaurants"]. delete_many (filter_builder.view ());
        // @end: cpp-remove-matching-documents
    }

    // Remove one document that matches a condition.
    {
        // @begin: cpp-remove-justone
        bsoncxx :: builder :: stream :: document filter_builder;
        filter_builder << "borough"
                       << "Queens";

        db ["restaurants"]. delete_one (filter_builder.view ());
        // @end: cpp-remove-justone
    }

    // Remove all documents in a collection.
    {
        // @begin: cpp-remove-all-documents
        db ["restaurants"]. delete_many ({});
        // @end: cpp-remove-all-documents
    }

    // Drop a collection.
    {
        // @begin: cpp-drop-collection
        db ["restaurants"]. drop ();
        // @end: cpp-drop-collection
    }
}
2.5 query.cpp:Query for all file conditions in a collection query that contains a key value pair contains a key value pair (the value is document, and the nested query continues in document) The conditional query contains a key value pair (value is array, Continue nested queries in array) using $GT (greater than), $lt (less than) conditionally query multiple condition queries equal to and satisfy at least one condition query in multiple conditions, equivalent to or in SQL to sort query results
int main (int, char **) {
    mongocxx :: instance inst {};
    mongocxx :: client conn {mongocxx :: uri {}};

    auto db = conn ["test"];

    // Query for all the documents in a collection.
    // Query all documents in the restaurant collection of the test database
    {
        // @begin: cpp-query-all
        auto cursor = db ["restaurants"]. find ({});
        for (auto && doc: cursor) {
            std :: cout << bsoncxx :: to_json (doc) << std :: endl;
        }
        // @end: cpp-query-all
    }

    // Query for equality on a top level field.
    // Query all documents containing "borough": "Manhattan" key-value pairs in the restaurants collection
    {
        // @begin: cpp-query-top-level-field
        auto cursor = db ["restaurants"]. find (document {} << "borough"
                                                        << "Manhattan" << finalize);

        for (auto && doc: cursor) {
            std :: cout << bsoncxx :: to_json (doc) << std :: endl;
        }
        // @end: cpp-query-top-level-field
    }

    // Query by a field in an embedded document.
    // Nested query, query the document of the restaurant with zip code 10075, address is a document nested in the document, zipcode is a key in address, and 10075 is the value corresponding to zipcode.
    {
        // @begin: cpp-query-embedded-document
        bsoncxx :: builder :: stream :: document filter_builder;
        filter_builder << "address.zipcode"
                       << "10075";

        auto cursor = db ["restaurants"]. find (filter_builder.view ());
        for (auto && doc: cursor) {
            std :: cout << bsoncxx :: to_json (doc) << std :: endl;
        }
        // @end: cpp-query-embedded-document
    }

    // Query by a field in an array.
    // The value corresponding to the grades key is an array with two documents in it. Look for the document whose grade key value is B in this array
    {
        // @begin: cpp-query-field-in-array
        bsoncxx :: builder :: stream :: document filter_builder;
        filter_builder << "grades.grade"
                       << "B";

        auto cursor = db ["restaurants"]. find (filter_builder.view ());
        for (auto && doc: cursor) {
            std :: cout << bsoncxx :: to_json (doc) << std :: endl;
        }
        // @end: cpp-query-field-in-array
    }

    // Query with the greater-than operator ($ gt).
    // Find documents with a score greater than 30 in the array corresponding to grades
    {
        // @begin: cpp-query-greater-than
        bsoncxx :: builder :: stream :: document filter_builder;
        filter_builder << "grades.score" << open_document << "$ gt" << 30 << close_document;

        auto cursor = db ["restaurants"]. find (filter_builder.view ());
        for (auto && doc: cursor) {
            std :: cout << bsoncxx :: to_json (doc) << std :: endl;
        }
        // @end: cpp-query-greater-than
    }

    // Query with the less-than operator ($ lt).
    // $ gt and $ lt are greater than and less than
    {
        // @begin: cpp-query-less-than
        bsoncxx :: builder :: stream :: document filter_builder;
        filter_builder << "grades.score" << open_document << "$ lt" << 10 << close_document;

        auto cursor = db ["restaurants"]. find (filter_builder.view ());
        for (auto && doc: cursor) {
            std :: cout << bsoncxx :: to_json (doc) << std :: endl;
        }
        // @end: cpp-query-less-than
    }

    // Query with a logical conjunction (AND) of query conditions.
    // There are multiple key-value pairs in filter_builder, and the default is the relationship of and, which is equivalent to and in the SQL statement, which indicates that the query documents for restaurants where Italian is Italian and zipcode is 10075
    {
        // @begin: cpp-query-logical-and
        bsoncxx :: builder :: stream :: document filter_builder;
        filter_builder << "cuisine"
                       << "Italian"
                       << "address.zipcode"
                       << "10075";

        auto cursor = db ["restaurants"]. find (filter_builder.view ());
        for (auto && doc: cursor) {
            std :: cout << bsoncxx :: to_json (doc) << std :: endl;
        }
        // @end: cpp-query-logical-and
    }

    // Query with a logical disjunction (OR) of query conditions.
    // $ or indicates the relationship of OR Note the use of open_array / close_array and open_document / close_document at this place
    {
        // @begin: cpp-query-logical-or
        bsoncxx :: builder :: stream :: document filter_builder;
        filter_builder << "$ or" << open_array << open_document << "cuisine"
                       << "Italian" << close_document << open_document << "address.zipcode"
                       << "10075" << close_document << close_array;

        auto cursor = db ["restaurants"]. find (filter_builder.view ());
        for (auto && doc: cursor) {
            std :: cout << bsoncxx :: to_json (doc) << std :: endl;
        }
        // @end: cpp-query-logical-or
    }

    // Sort query results.
    // 1 and -1 indicate ascending and descending order (should be)
    {
        // @begin: cpp-query-sort
        mongocxx :: options :: find opts;
        bsoncxx :: builder :: stream :: document order_builder;
        order_builder << "borough" << 1 << "address.zipcode" << -1;
        opts.sort (order_builder.view ());

        auto cursor = db ["restaurants"]. find ({}, opts);
        for (auto && doc: cursor) {
            std :: cout << bsoncxx :: to_json (doc) << std :: endl;
        }
        // @end: cpp-query-sort
    }
}
2.6 Get_values_from_documents.cpp


Data from the document of the database, output to cout


using bsoncxx :: builder :: stream :: document;
using bsoncxx :: builder :: stream :: close_array;
using bsoncxx :: builder :: stream :: finalize;
using bsoncxx :: builder :: stream :: open_array;
using bsoncxx :: type;

// Document model, showing array with nested documents:
//
// {
// "_id": ObjectId (...),
// "messagelist": [
// {
// "uid": 413098706,
// "status": 2,
// "msg": "..."
//},
// ...
//]
//}

// Construct a document in the format of 'messagelist'.
bsoncxx :: document :: value new_message (int64_t uid, int32_t status, std :: string msg) {
    document doc;
    return doc << "uid" << uid << "status" << status << "msg" << msg << finalize;
}

// Insert a document into the database.
void insert_test_data (mongocxx :: collection & coll) {
    document builder {};
    // Note this assignment method
    builder << "messagelist" << open_array << new_message (413098706, 3, "Lorem ipsum ...")
            << new_message (413098707, 2, "Lorem ipsum ...")
            << new_message (413098708, 1, "Lorem ipsum ...") << close_array;

    bsoncxx :: document :: value doc = builder << finalize;

    // Normally, one should check the return value for success.
    coll.insert_one (doc.view ());
}

// Iterate over contents of messagelist. Iterate over everything in the messagelist array
void iterate_messagelist (const bsoncxx :: document :: element & ele) {
    // Check validity and type before trying to iterate.
    if (ele.type () == type :: k_array) {
        bsoncxx :: array :: view subarray {ele.get_array (). value};
        for (const bsoncxx :: array :: element & msg: subarray) {
            // Check correct type before trying to access elements.
            // Only print out fields if they exist; don't report missing fields.
            if (msg.type () == type :: k_document) {
                bsoncxx :: document :: view subdoc = msg.get_document (). value;
                bsoncxx :: document :: element uid = subdoc ["uid"]; // Use the [] access key
                bsoncxx :: document :: element status = subdoc ["status"];
                bsoncxx :: document :: element msg = subdoc ["msg"];
                if (uid && uid.type () == type :: k_int64) {
                    std :: cout << "uid:" << uid.get_int64 (). value << std :: endl;
                }
                if (status && status.type () == type :: k_int32) {
                    std :: 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.