首页 > 解决方案 > 这是因为我输入的数字太大而导致查询错误吗?

问题描述

我正在尝试编写一个 C++ 程序来查找位置并读取其数据。我需要查询一个 mongodb,我在其中存储有关每个文档中某个位置的信息。

我已经创建了与数据库的连接,并且可以找到集合中的所有文档。当我尝试构建一个 find() 查询以匹配基于其纬度和经度的位置时,我收到错误:

ReadStationData.cc:109:64: error: narrowing conversion of ‘3.9400500000000001e+1’ from ‘double’ to ‘std::size_t {aka long unsigned int}’ inside { } [-Wnarrowing]
       auto cursor = coll.find({{"lat" , 39.400500000000000966}});

我的代码:


#include <cstdlib>
#include <iostream>
#include <string>

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/stdx/make_unique.hpp>

#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/logger.hpp>
#include <mongocxx/options/client.hpp>
#include <mongocxx/uri.hpp>


int main(int argc, char* argv[]) {
    using bsoncxx::builder::basic::kvp;
    using bsoncxx::builder::basic::make_document;

mongocxx::instance inst{bsoncxx::stdx::make_unique};

    try {
        const auto uri = mongocxx::uri{"mongodb://user:pswd@32.445.67.89/snowdb?authSource=admin"};

        mongocxx::options::client client_options;
        if (uri.ssl()) {
            mongocxx::options::ssl ssl_options;
            client_options.ssl_opts(ssl_options);
        }
        auto client = mongocxx::client{uri, client_options};
        auto admin = client["admin"];
        auto result = admin.run_command(make_document(kvp("isMaster", 1)));

        std::cout << bsoncxx::to_json(result) << "\n";


    mongocxx::database db = client["snowdb"];
    mongocxx::collection coll = db["Location"];

using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_array;
using bsoncxx::builder::basic::make_document;

      auto cursor = coll.find({{"lat" , 39.400500000000000966}});

        for (auto&& doc : cursor) {
            std::cout << bsoncxx::to_json(doc) << std::endl;
}
}

以下是数据的外观:

{ "_id" : { "$oid" : "5d02ea10f21300007c1b7274" }, 
"lat" : [ 41.0367999999999995 ], 
"lon" : [ -105.12600000000000477 ], .....

标签: c++mongodb-query

解决方案


这样做的问题是数据值在列表 [] 中,我没有用数组包围该值,如下所示:

auto cursor=coll.find(make_document(kvp("lon", make_array(-105.12000000000000455))));


推荐阅读