如何解决mongocxx 中的特定字段值
我想使用 mongocxx 在我的 mongodb 中拥有特定字段的所有值。我的集合中有 100 个文档,每个文档都有一个字段“X1_position”,该字段的值是浮动的。我想获取该字段的所有 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)
请帮帮我
解决方法
我认为您所追求的是projection。 你不需要过滤,因为你说你想要所有的文档,但你需要告诉 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" }
我只想得到 valye 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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。