Home > other >  How to split a string into array of letters in MongoDB aggregation framework?
How to split a string into array of letters in MongoDB aggregation framework?

Time:09-16

I want to split a string into array of letters just like we do in javascript, Eg,

let x = "String";
x.split('') // ['S', 't', 'r', 'i', 'n', 'g']

But, if I do the same using $split in aggregation pipeline, like below,

{
 $project:{
 _id:"$_id._id",
 name:"$_id.name",
 array_field:{ $split: ["$_id.name", ""] }
 }
}

its throwing me error like this,

{
    "message" : "PlanExecutor error during aggregation :: caused by :: $split requires a non-empty separator",
    "ok" : 0,
    "code" : 40087,
    "codeName" : "Location40087",
    "name" : "MongoError"
}

can anyone help me out with this problem. thanks.

CodePudding user response:

...$split requires a non-empty separator

That is the expected error when you split a string (using $split aggregate operator) with a "" (string with zero length) as a delimiter.

You can try this approach to get the desired result (this splits the string field str: "string" to an array field arr: [ "s", "t", "r", "i", "n", "g" ]):

db.collection.aggregate([
  { 
      $addFields: { 
          arr: {
              $function: {
                  body: function(s) {
                               return s.split('');
                  },
                  args: [ "$str" ],
                  lang: "js"
              }
          }
      }
  }
])

Note that the usage of $function requires MongoDB v4.4.

CodePudding user response:

I recommend you combined $substr with $map, we will iterate over the length of the string and use $substr to select the character at index i, like so:

db.collection.aggregate([
  {
    "$addFields": {
      "newField": {
        $map: {
          input: {
            $range: [
              0,
              {
                "$strLenCP": "$key"
              }
            ]
          },
          in: {
            "$substr": [
              "$key",
              "$$this",
              1
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

  • Related