Data:
{code: "XXXXXXXX1", total: 400},
{code: "YYYYY2", total: 500}
{code: "ZZZZZZ3", total: 100}
{code: "AAA5", totala: 200}
I want to create an aggregate function to group the data above by its last character in the code
field. code
field is a string and can be varied in length. I only want to get its last index/number. Something like:
db.transactions.aggregate([
{$project: {
last_index: {$getMyLastCharInMyCode: "$code"},
total: 1
}},
{$group: {_id: "$last_index", {total: {$sum: "$total"}}}}
])
I searched the internet and mongodb manuals, it seems impossible. Any ideas? Thank you
Copyright Notice:Content Author:「DennyHiu」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/49684970/how-to-get-last-character-from-a-string-in-mongodb