Search code examples
javascriptmongodbaggregate

Mongodb aggregate - remove whitespace and letters from name


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?


Solution

  • Query

    • we dont have a regex-replace in mongodb yet, but we have a regex-find, so we can do it using a reduce also

    *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

    Playmongo

    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

    Playmongo

    aggregate(
    [{"$set": 
       {"name": 
         {"$reduce": 
           {"input": {"$regexFindAll": {"input": "$name", "regex": "\\d+"}},
            "initialValue": "",
            "in": {"$concat": ["$$value", "$$this.match"]}}}}}])