I can't find how to replace the whiteSpace in a aggregate request with MongoDB and how to delete a part of a string.(I'll probably need to use a regex).
Example of my document:
{
"_id": "57dfa5c9xxd76b65426d5cca",
"battle_id": "5744f01d1ad716a349c4999a",
"is_first": false,
"title": "division 1 #3"
},
{
"_id": "13dfa529dxd123x5426d5ccb",
"battle_id": "1244x51d1aq546a349c423rcc",
"is_first": true,
"title": "division gold #5"
}
What I'm doing currently:
.project({
"battle_id": "$battle_id",
"is_first": {
$cond: [
{ $eq : ["$rank" , 1] },
true,
false
]
},
"title": { $toLower: "$battle.title" }
})
Is it possible to change each white space by "_" character or do I need to do it in a forEach() after the request?
Moreover, is it possible to format the string to never return me the #3 for example?
Result that I need (changes are in title):
{
"_id": "57dfa5c9xxd76b65426d5cca",
"battle_id": "5744f01d1ad716a349c4999a",
"is_first": false,
"title": "division_1"
},
{
"_id": "13dfa529dxd123x5426d5ccb",
"battle_id": "1244x51d1aq546a349c423rcc",
"is_first": true,
"title": "division_gold"
}
You can replace white space and format string by using Regular Expressions and Array#map() to get the 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);