🚀 Nuova versione beta disponibile! Feedback o problemi? Contattaci

Esercizi Query Avanzate MongoDB C++

Codegrind Team•Jul 12 2024

Ecco degli esercizi semplici con soluzione per praticare l’utilizzo di query avanzate in MongoDB utilizzando C++.

Esercizio 1: Query con filtro e proiezione

Creare una query che filtra i documenti in base a un campo specifico e proietta solo determinati campi.
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <iostream>

int main() {
    mongocxx::instance instance{};
    mongocxx::client client{mongocxx::uri{"mongodb://localhost:27017"}};
    auto collection = client["test_db"]["test_collection"];

    bsoncxx::builder::basic::document filter{};
    filter.append(bsoncxx::builder::basic::kvp("age", bsoncxx::builder::basic::make_document(
        bsoncxx::builder::basic::kvp("$gte", 30)
    )));

    bsoncxx::builder::basic::document projection{};
    projection.append(bsoncxx::builder::basic::kvp("name", 1),
                      bsoncxx::builder::basic::kvp("_id", 0));

    auto cursor = collection.find(filter.view(), mongocxx::options::find{}.projection(projection.view()));

    for (auto&& doc : cursor) {
        std::cout << bsoncxx::to_json(doc) << std::endl;
    }

    return 0;
}

Esercizio 2: Query con ordinamento

Creare una query che ordina i documenti in base a un campo specifico.
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <iostream>

int main() {
    mongocxx::instance instance{};
    mongocxx::client client{mongocxx::uri{"mongodb://localhost:27017"}};
    auto collection = client["test_db"]["test_collection"];

    bsoncxx::builder::basic::document sort{};
    sort.append(bsoncxx::builder::basic::kvp("name", 1)); // 1 per ascendente, -1 per discendente

    auto cursor = collection.find({}, mongocxx::options::find{}.sort(sort.view()));

    for (auto&& doc : cursor) {
        std::cout << bsoncxx::to_json(doc) << std::endl;
    }

    return 0;
}

Esercizio 3: Query con limitazione dei risultati

Creare una query che limita il numero di documenti restituiti.
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <bsoncxx/json.hpp>
#include <iostream>

int main() {
    mongocxx::instance instance{};
    mongocxx::client client{mongocxx::uri{"mongodb://localhost:27017"}};
    auto collection = client["test_db"]["test_collection"];

    auto cursor = collection.find({}, mongocxx::options::find{}.limit(5));

    for (auto&& doc : cursor) {
        std::cout << bsoncxx::to_json(doc) << std::endl;
    }

    return 0;
}

Esercizio 4: Query con aggregazione (pipeline semplice)

Creare una pipeline di aggregazione per raggruppare i documenti e calcolare il valore medio di un campo.
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/array.hpp>
#include <iostream>

int main() {
    mongocxx::instance instance{};
    mongocxx::client client{mongocxx::uri{"mongodb://localhost:27017"}};
    auto collection = client["test_db"]["test_collection"];

    using bsoncxx::builder::basic::kvp;
    using bsoncxx::builder::basic::make_document;
    using bsoncxx::builder::basic::make_array;

    auto pipeline = mongocxx::pipeline{};
    pipeline.group(make_document(kvp("_id", "$department"),
                                 kvp("averageAge", make_document(kvp("$avg", "$age")))));

    auto cursor = collection.aggregate(pipeline);

    for (auto&& doc : cursor) {
        std::cout << bsoncxx::to_json(doc) << std::endl;
    }

    return 0;
}

Esercizio 5: Query con ricerca testuale

Creare una query che esegue una ricerca testuale su un campo indicizzato per testo.
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <iostream>

int main() {
    mongocxx::instance instance{};
    mongocxx::client client{mongocxx::uri{"mongodb://localhost:27017"}};
    auto collection = client["test_db"]["test_collection"];

    bsoncxx::builder::basic::document filter{};
    filter.append(bsoncxx::builder::basic::kvp("$text", bsoncxx::builder::basic::make_document(
        bsoncxx::builder::basic::kvp("$search", "search term")
    )));

    auto cursor = collection.find(filter.view());

    for (auto&& doc : cursor) {
        std::cout << bsoncxx::to_json(doc) << std::endl;
    }

    return 0;
}

Esercizio 6: Query con condizioni multiple

Creare una query che utilizza condizioni multiple (AND, OR) per filtrare i documenti.
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <iostream>

int main() {
    mongocxx::instance instance{};
    mongocxx::client client{mongocxx::uri{"mongodb://localhost:27017"}};
    auto collection = client["test_db"]["test_collection"];

    bsoncxx::builder::basic::document filter{};
    filter.append(bsoncxx::builder::basic::kvp("$and", bsoncxx::builder::basic::make_array(
        bsoncxx::builder::basic::make_document(bsoncxx::builder::basic::kvp("age", bsoncxx::builder::basic::make_document(bsoncxx::builder::basic::kvp("$gte", 25)))),
        bsoncxx::builder::basic::make_document(bsoncxx::builder::basic::kvp("status", "active"))
    )));

    auto cursor = collection.find(filter.view());

    for (auto&& doc : cursor) {
        std::cout << bsoncxx::to_json(doc) << std::endl;
    }

    return 0;
}