2016-08-23 30 views
1

说检索特定字段的值,我插使用蒙戈命令行或shell下列文件:如何使用蒙戈CXX司机

db.Users.insert( 
    { 
     "user info":{ 
      "user name" : "Joe", 
      "password" : "[email protected]#%$%" , 
      "Facebook" : "aaa", 
      "Google" : "joe z" 
     } 
    } 
) 

那么这个输入登录到与创建的系统数据库ID。

如果我想实现下面的命令行,它只返回特定字段的值(在这种情况下是_id),使用cxx驱动程序我应该怎么做?

这是命令行:

db.Users.find({"user info.user name": "Joe"}, {"_id":1}) 

我尝试下面的C++代码

bsoncxx::builder::stream::document document{} ; 
document<<"user info.user name"<<"Joe"<<"_id"<<1; 
auto cursor = myCollection.find(document.view()); 

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

它只是给我什么。

如果我设置

document<<"user info.user name"<<"Joe" 

然后返回整个JSON消息给我。

请让我知道你是否有更好的点子。

+1

要包括在查询中,这是行不通的突出部分。提供一个'''''mongocxx :: options :: find'''对象作为mongocxx :: collection :: find'''的第二个参数,通过调用mongocxx :: options :: find :: projection'''方法。 – acm

+0

感谢您的回复,请给我看一些例子或链接? – Joe

回答

3

下面是一个例子:

#include <iostream> 

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

#include <mongocxx/client.hpp> 
#include <mongocxx/options/find.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::finalize; 

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

    auto coll = conn["test"]["foo"]; 
    coll.drop(); 

    // Insert a test document 
    auto joe = document{} << "user info" << open_document << "user name" 
         << "Joe" << close_document << finalize;  
    auto result = coll.insert_one(joe.view()); 
    std::cout << "Inserted " << result->inserted_id().get_oid().value.to_string() 
      << std::endl; 

    // Create the query filter 
    auto filter = document{} << "user info.user name" 
          << "Joe" << finalize; 

    // Create the find options with the projection 
    mongocxx::options::find opts{}; 
    opts.projection(document{} << "_id" << 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; 
    } 
} 
+0

非常感谢您的回答,先生。我看到你是mongo db的软件工程师,是否有可能建议mongo在cxx驱动程序教程/文档中添加更多示例? – Joe

+0

@Joe - 已经在进行中:https://github.com/mongodb/mongo-cxx-driver/pull/519 – acm

+1

我发现“最终确定”有点错误。如果我最后确定,它会返回一切。但是,如果我删除了finalize,它只会返回“_id”,这是预期的行为。您可能还想在opts.projection()中使用document.view()。无论如何非常感谢您的帮助。 – Joe