如何使用mongo cxx驱动程序检索特定字段的值

Joe*_*Joe 1 mongodb mongo-cxx-driver

说,我使用mongo命令行或shell插入了以下文档:

db.Users.insert( 
    { 
        "user info":{ 
            "user name" : "Joe", 
            "password" : "!@#%$%" ,
            "Facebook" : "aaa", 
            "Google" : "joe z"
        }
    }
)
Run Code Online (Sandbox Code Playgroud)

然后,此条目将使用系统创建的ID登录到数据库。

如果我想实现仅返回特定字段(在这种情况下为_id)的值的以下命令行,如何使用cxx驱动程序呢?

这是命令行:

db.Users.find({"user info.user name": "Joe"}, {"_id":1})
Run Code Online (Sandbox Code Playgroud)

我尝试了以下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;
 }
Run Code Online (Sandbox Code Playgroud)

它简直一无所有。

如果我设置

document<<"user info.user name"<<"Joe"
Run Code Online (Sandbox Code Playgroud)

然后,它将为我返回整个JSON消息。

如果您有更好的主意,请告诉我。

xdg*_*xdg 6

这是一个例子:

#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;
  }
}
Run Code Online (Sandbox Code Playgroud)