Search code examples
mongo-cxx-driver

Query for all fields


I have a mongo collection that looks like this

db.SymbolMCIpPort.find()
{ "_id" : ObjectId("59f7bdaee23020650635ed3c"), "Provider" : "BROKER1", "Symbol" : "EURUSD", "MCIpPort" : { "IP" : "224.0.0.1", "PORT" : "12345" } }
{ "_id" : ObjectId("59f7bdaee23020650635ed3d"), "Provider" : "BROKER1", "Symbol" : "EURJPY", "MCIpPort" : { "IP" : "224.0.0.1", "PORT" : "12346" } }

I am trying to query it to find all the fields that match EURUSD, like this:

// Create the query filter
auto filter = document{} << "Symbol" << "EURUSD"
                             << finalize;
// Create the find options with the projection
mongocxx::options::find opts{};
opts.projection(document{} << "_id" << "Provider" << "Symbol" << 1 << finalize);

// Execute find with options
auto cursor = coll.find(filter.view(), opts);
for (auto &&doc : cursor) {
    std::cout << bsoncxx::to_json(doc) << std::endl;
}

But it only gets me two fields, the id and Symbol [I am even confused why I don't also get the Provider field let alone the rest of the fields that match EURUSD.]

{ "_id" : { "$oid" : "59f7bdaee23020650635ed3c" }, "Symbol" : "EURUSD" }

How do I modify the code to get all the fields?


Solution

  • I solved it slightly differently with find_one:

    auto filter = document{} << "Symbol" << rawSymbol
                                         << finalize;
    
    bsoncxx::stdx::optional<bsoncxx::document::value> maybe_result = coll.find_one(filter.view());
    if(maybe_result) {
        std::cout << bsoncxx::to_json(*maybe_result) << "\n";
    }