Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't convert a Number to String using $toString

I'm studying MongoDB (version 4.0.0) aggregate feature but I can't make a simple $toString to work fine. When I remove the $toString operator I get the following output:

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

But when I try to convert the field payment_date_formatted, everything goes wrong and the output is:

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

Why this is happening? This is the aggregate call:

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"}
    }
  }
]);
like image 617
Sandro Simas Avatar asked Nov 22 '25 13:11

Sandro Simas


1 Answers

You need to use $toLong and $toString aggregation simultaneously here

db.payment_orders.aggregate([
  {
    "$project": {
      "payment_date": { "$toLong": "$payment_date" },
      "payment_date_formatted": {
        "$toString": { "$toLong": "$payment_date_formatted" }
      }
    }
  }
])

You can try it here

like image 195
Ashh Avatar answered Nov 24 '25 05:11

Ashh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!