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"}
}
}
]);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With