我想使用mongocxx在mongodb中拥有特定字段的所有值。我的集合中有100个文档,每个文档都有一个字段“ X1_position”,该字段的值是float。我想获取该字段的所有100个值,并将其存储到数组中。我正在使用以下代码,但无法正常工作
#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["my_data"]["exp1"];
bsoncxx::builder::stream::document mydoc;
mydoc << "X1_Position";
mongocxx::cursor cursor = coll.find( mydoc.view() );
for(auto &&doc : cursor) {
std::cout << doc["X1_ActualPosition"].get_utf8().value << "\n";
}
}
它编译良好,但是在运行可执行文件时出现以下错误。
./testmongo
terminate called after throwing an instance of 'bsoncxx::v_noabi::exception'
what(): can't convert builder to a valid view: unmatched key
Aborted (core dumped)
请帮我
我认为您追求的是投射。您不需要过滤,因为您说过想要所有文档,但是您需要告诉MongoDB您想要返回哪些字段:
auto coll = conn["my_data"]["exp1"];
bsoncxx::builder::stream::document mydoc;
// Use projection to pick the field you want
// _id must be explicitly removed since it is returned by default
bsoncxx::builder::stream::document myprojection;
myprojection << "X1_ActualPosition" << 1 << "_id" << 0;
mongocxx::options::find opts{};
opts.projection(myprojection.view());
mongocxx::cursor cursor = coll.find(mydoc.view(), opts);
for (auto &&doc : cursor) {
std::cout << doc["X1_ActualPosition"].get_double() << std::endl;
}
您收到的错误是因为您正在尝试构建传递不带任何值的键的查询来过滤文档的查询,我认为在mongodb解释器中执行以下操作(这也会崩溃)类似于:
db.exp1.find({"X1_ActualPosition"}) // ERROR: SyntaxError: missing : after property id
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句