Mongodb 将十进制转换为字符串-mongoose

Mongodb 将十进制转换为字符串-mongoose,mongodb,mongoose,Mongodb,Mongoose,所以我注意到我的一些位置数据被存储为十进制,这很好,但现在我需要将它们显示为字符串 我想知道如何将小数转换成字符串 location.find({},'location').limit(5000).exec(function(err,result) { if(err){ res.send(err) } console.log(result) // string = "eqfeed_callback('

所以我注意到我的一些位置数据被存储为十进制,这很好,但现在我需要将它们显示为字符串

我想知道如何将小数转换成字符串

location.find({},'location').limit(5000).exec(function(err,result) {
        if(err){
            res.send(err)
        }
        console.log(result)
       // string = "eqfeed_callback('features':["+result+"])";
        res.json(result);
        
    });
我知道我需要使用
{$convert:{input:,to:“string”}

但是在哪里呢

我试过:

$addFields:{
  loc: { $toString: "$location.coordinates[0]" }
}
但是没有成功

我试了一下下面的答案,得到了答案

const location = require('mongoose').model('listenerslocation');
    location.find({},
        {
          location: {
            coordinates: {
              $map: {
                input: "$location.coordinates",
                in: {
                  $toString: "$$this"
                }
              }
            }
          }
        }).exec(function(err,result) {
        if(err){
            res.send(err)
        }
        console.log(result)
       // string = "eqfeed_callback('features':["+result+"])";
        res.json(result);
和错误

{"operationTime":"6887428625520394251","ok":0,"code":2,"codeName":"BadValue","$clusterTime":{"clusterTime":"6887428625520394251","signature":{"hash":"0WZkZ4Rt5ldDlszBCucqYlEXedw=","keyId":"6852375211279384577"}},"name":"MongoError"}
这是原始JSON

{"coordinates":[{"$numberDecimal":"115.91138270694381"},{"$numberDecimal":"-31.88770435287793"}],"currentTime":1599186425260}
你可以试试

  • $map
    迭代
    坐标数组的循环,并
    $toString
    转换字符串中的类型
MongoDB 4.4或更高版本

  • 从MongoDB 4.4开始,作为使投影与聚合的
    $project
    阶段一致的一部分


任何MongoDB版本

  • 使用方法和
    $addFields
    更新位置字段

发送到客户端后无法设置头文件我收到的错误为{“operationTime”:“6887428625520394251”,“ok”:0,“code”:2,“codeName”:“BadValue”,“$clusterTime”:{“clusterTime”:“6887428625520394251”,“签名”:{“hash”:“0WZKZ4RT5LDSzbcucqylexedw=,“keyId”:“6852375211279384577”},“name”:“MongoError”}我不确定你的mongodb到底是什么版本的?因为这将在版本4.4中提供支持,请告诉我,如果您的mongodb版本低于4.4,那么您必须使用聚合()我正在使用mongoose(“mongoose”:“^5.10.10”)和mongodb Atlas(4.2.10)。它不起作用-我仍然得到
{“$numberDecimal”:-31.941225025832598”}
location.find({},
{
  "location.coordinates": {
    $map: {
      input: "$location.coordinates",
      in: { $toString: "$$this" }
    }
  }
})
location.aggregate([
  {
    $addFields: {
      "location.coordinates": {
        $map: {
          input: "$location.coordinates",
          in: { $toString: "$$this" }
        }
      }
    }
  },
  { $limit: 5000 }
])