将十进制转换为字符串-猫鼬

时间:2020-10-25 04:56:36

标签: mongodb mongoose

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

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

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: <expression>, 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"}

这是RAW JSON

{"coordinates":[{"$numberDecimal":"115.91138270694381"},{"$numberDecimal":"-31.88770435287793"}],"currentTime":1599186425260}

1 个答案:

答案 0 :(得分:0)

您可以尝试

  • $map迭代coordinates数组循环和$toString循环转换字符串中的类型

MongoDB 4.4或更高版本

  • 从MongoDB 4.4开始,作为使find()投影与聚合的$project阶段保持一致的一部分
location.find({},
{
  "location.coordinates": {
    $map: {
      input: "$location.coordinates",
      in: { $toString: "$$this" }
    }
  }
})

Playground


任何MongoDB版本

  • 使用aggregate()方法和$addFields更新位置字段
location.aggregate([
  {
    $addFields: {
      "location.coordinates": {
        $map: {
          input: "$location.coordinates",
          in: { $toString: "$$this" }
        }
      }
    }
  },
  { $limit: 5000 }
])

Playground

相关问题