我想有一个特定字段的所有值在我的mongodb使用mongocxx。我的集合中有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
非常感谢您的回复。通过运行命令
,我得到了以下输出"std::cout << bsoncxx::to_json(doc) << "n";
output
{ "X1_ActualPosition" : "1.41E+02" }
我只想得到值141。我如何删除第一个标题字符串,以及如何将第二个字符串转换为整数或双精度?下面的代码给了我错误
std::cout << doc["X1_ActualPosition"].get_double() << std::endl;
误差
terminate called after throwing an instance of 'bsoncxx::v_noabi::exception'
what(): expected element type k_double
Aborted (core dumped)