如何从mongodb中的字符串中获取最后一个字符? [英] how to get last character from a string in mongodb?

查看:59
本文介绍了如何从mongodb中的字符串中获取最后一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据:

{code: "XXXXXXXX1", total: 400},
{code: "YYYYY2", total: 500}
{code: "ZZZZZZ3", total: 100}
{code: "AAA5", totala: 200}

我想创建一个聚合函数,将上面的数据按 code 字段中的最后一个字符分组.code 字段是一个字符串,长度可以变化.我只想得到它的最后一个索引/编号.类似的东西:

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"}}}}
])

我在网上和 mongodb 手册上搜索过,似乎不可能.有任何想法吗?谢谢

I searched the internet and mongodb manuals, it seems impossible. Any ideas? Thank you

推荐答案

给你:

db.transactions.aggregate({
    $addFields: {
        "last_index": { $substr: [ "$code", { $subtract: [ { $strLenCP: "$code" }, 1 ] }, 1 ] }
    }
})

这篇关于如何从mongodb中的字符串中获取最后一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆