查询所有字段

时间:2017-10-31 00:29:37

标签: mongo-cxx-driver

我有一个看起来像这样的mongo集合

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" } }

我正在尝试查询它以查找与EURUSD匹配的所有字段,如下所示:

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

但它只给我两个字段,idSymbol [我甚至感到困惑,为什么我也不能获得Provider字段,更不用说其余字段了符合EURUSD的字段。]

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

如何修改代码以获取所有字段?

1 个答案:

答案 0 :(得分:1)

我使用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";
}