Reputation:
I have the following group function in my mongodb aggregate:
{
$group: {
_id: "$group.name",
studentSchoolIDs: {
$push: "$student_school._id",
},
},
},
This works fine, however before this, i would like to change the group names to remove any spaces or letters. For example "Y 2" would become "2" and "Year 2" would become "2". Is there a way to do that in the aggregate?
Upvotes: 2
Views: 123
Reputation: 8695
Query
*you can put the reduce on grouping, or you do it after on the _id
for example replace "name" with "_id" after the group
To remove letters and spaces
aggregate(
[{"$set":
{"name":
{"$reduce":
{"input":
{"$regexFindAll": {"input": "$name", "regex": "[a-zA-Z]+|\\s+"}},
"initialValue": "$name",
"in":
{"$replaceOne":
{"input": "$$value", "find": "$$this.match", "replacement": ""}}}}}}])
To keep only the digits
aggregate(
[{"$set":
{"name":
{"$reduce":
{"input": {"$regexFindAll": {"input": "$name", "regex": "\\d+"}},
"initialValue": "",
"in": {"$concat": ["$$value", "$$this.match"]}}}}}])
Upvotes: 1