the js document非常缺乏。
但是,c ++驱动程序的语法通常具有与js语法的一对一映射。因此,如果未发现有关使用c ++驱动程序的某些信息,通常可以模仿js代码。
但是对于以下任务(found on the js document),我找不到正确的c ++解决方案:
查询数组中的元素
查询数组字段是否包含 至少一个具有指定值的元素,请使用过滤器{: }元素值在哪里。以下示例查询所有标签为数组的文档 包含字符串“ red”作为其元素之一:
db.inventory.find( { tags: "red" } )
我当前的代码:
mongocxx::cursor cursor =
inventoryCollection.find(bsoncxx::builder::stream::document{}
<< "tags" << "red"
<< bsoncxx::builder::stream::close_document
<< bsoncxx::builder::stream::finalize);
这将导致异常。显然,对于数组字段,不允许给它一个字符串作为搜索查询:“ tags” <<“ red”
我应该如何在c ++中实现?
答案 0 :(得分:1)
https://github.com/xyz347/mongoxclient 这是mongo-cxx-driver的简单包装
您可以这样编写代码:
// init mongocx::Collection col
col.Find({{"tags", "red"}}).One(xxx); // xxx is a struct reference to receive result
完整示例:
#include <iostream>
#include <mongocxx/client.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/instance.hpp>
#include "mongoxclient.hpp" // include mongoxclient.hpp
mongocxx::instance instance{};
using namespace std;
// structure define
struct User {
int uid;
string name;
int age;
string tags;
XTOSTRUCT(A(uid, "bson:_id"), O(name, age, tags)); // add XTOSTRUCT macro(https://github.com/xyz347/x2struct),use uid as _id
};
int main(int argc, char *argv[]) {
mongocxx::uri uri("mongodb://test:test@127.0.0.1:27018/test");
mongocxx::client client(uri);
mongocxx::collection collect = client["test"]["test"];
mongoxc::Collection col(collect); // construct mongoxc::Collection with mongocxx::collection
User result;
col.Find({{"tags","red"}}).One(result); // find one.
cout<<x2struct::X::tojson(result)<<endl;
return 0;
}
答案 1 :(得分:0)
我认为您正在双重关闭信息流。消除对stream::close_document
的呼叫,只需让stream::finalize
为您完成。