数据:
{code: "XXXXXXXX1", total: 400},
{code: "YYYYY2", total: 500}
{code: "ZZZZZZ3", total: 100}
{code: "AAA5", totala: 200}
我想创建一个聚合函数,按照code
字段中的最后一个字符对上面的数据进行分组。 code
字段是一个字符串,长度可以变化。我只想得到它的最后一个索引/数字。类似的东西:
db.transactions.aggregate([
{$project: {
last_index: {$getMyLastCharInMyCode: "$code"},
total: 1
}},
{$group: {_id: "$last_index", {total: {$sum: "$total"}}}}
])
我搜索了互联网和mongodb手册,似乎不可能。有任何想法吗?谢谢
答案 0 :(得分:1)
你去了:
db.transactions.aggregate({
$addFields: {
"last_index": { $substr: [ "$code", { $subtract: [ { $strLenCP: "$code" }, 1 ] }, 1 ] }
}
})
答案 1 :(得分:0)
db.transactions.aggregate([
{"$project": {
total: 1,
code: 1,
last_index: { $substr: [ "$code", { $subtract: [ {"$strLenCP": "$code"}, 1 ] }, -1 ]}
}
},
{"$group": {
"_id": "$last_index",
"total": {"$sum": "$total"}
}
}
])