无法使用$ toString将数字转换为字符串

时间:2018-07-22 00:29:38

标签: mongodb aggregation-framework

我正在研究MongoDB(4.0.0版)聚合功能,但是我无法通过简单的$ toString正常工作。当我删除$ toString运算符时,我得到以下输出:

{ "_id" : ObjectId("5b4fa13c0ec5e844757333d5"), "payment_date" : 20180621, "payment_date_formatted" : 20180721 }
{ "_id" : ObjectId("5b4fa13c0ec5e844757333d7"), "payment_date" : 20180626, "payment_date_formatted" : 20180726 }

但是当我尝试转换字段payment_date_formatted时,一切都出错了,输出是:

{ "_id" : ObjectId("5b4fa13c0ec5e844757333d5"), "payment_date" : 20180621, "payment_date_formatted" : "2.01807e+07" }
{ "_id" : ObjectId("5b4fa13c0ec5e844757333d7"), "payment_date" : 20180626, "payment_date_formatted" : "2.01807e+07" }

为什么会这样?这是汇总调用:

db.payment_orders.aggregate([
  {
    "$match": {
      "company": ObjectId("5b368de558b52c13789edddd"),
      "payment_date": {
        "$gte": 20170601
      }
    }
  },
  {
    "$addFields": {
      "payment_date_formatted": {
        "$add": [
          "$payment_date",
          100
        ]
      }
    }
  },
  {
    "$project": {
      "payment_date": 1,
      "payment_date_formatted": {$toString: "$payment_date_formatted"}
    }
  }
]);

1 个答案:

答案 0 :(得分:0)

您需要在此处同时使用$toLong$toString聚合

nadvice

您可以尝试here