【问题标题】:Replace white space and format string替换空格和格式化字符串
【发布时间】:2017-06-02 14:56:51
【问题描述】:

我找不到如何用 MongoDB 替换 aggregate 请求中的 whiteSpace 以及如何删除字符串的一部分。(我可能需要使用正则表达式)。

我的文档示例:

{
    "_id": "57dfa5c9xxd76b65426d5cca",
    "battle_id": "5744f01d1ad716a349c4999a",
    "is_first": false,
    "title": "division 1 #3"
},    
{
    "_id": "13dfa529dxd123x5426d5ccb",
    "battle_id": "1244x51d1aq546a349c423rcc",
    "is_first": true,
    "title": "division gold #5"
}

我目前在做什么:

.project({
    "battle_id": "$battle_id",  
    "is_first": {
        $cond: [
            { $eq : ["$rank" , 1] }, 
            true, 
            false
        ]
    }, 
    "title": { $toLower: "$battle.title" }
})

是否可以通过"_" 字符更改每个空格,还是我需要在请求后在forEach() 中进行更改?

此外,是否可以将字符串格式化为从不返回#3

我需要的结果(标题有变化):

{
    "_id": "57dfa5c9xxd76b65426d5cca",
    "battle_id": "5744f01d1ad716a349c4999a",
    "is_first": false,
    "title": "division_1"
},    
{
    "_id": "13dfa529dxd123x5426d5ccb",
    "battle_id": "1244x51d1aq546a349c423rcc",
    "is_first": true,
    "title": "division_gold"
}

【问题讨论】:

    标签: javascript node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    您可以使用Regular ExpressionsArray#map() 替换空格和格式字符串以获得result

    var arr = [{"_id": "57dfa5c9xxd76b65426d5cca","battle_id": "5744f01d1ad716a349c4999a","is_first": false,"title": "division 1 #3"},{"_id": "13dfa529dxd123x5426d5ccb","battle_id": "1244x51d1aq546a349c423rcc","is_first": true,"title": "division gold #5"}],
        result = arr.map(i => {
          return {
            '_id': i._id,
            'battle_id': i.battle_id,
            'is_first': i.is_first,
            'title': i.title.replace(/\s#[0-9]+/g, '').replace(/\s/,'_')
          };
        });
    
    console.log(result);

    【讨论】:

    • 谢谢,所以没有合适的解决方案可以直接用 mongo 来做。所以谢谢你,我会继续这样下去。
    猜你喜欢
    • 2015-08-03
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    相关资源
    最近更新 更多