hardcode
hardcode

Reputation: 405

How to replace text in split sub-string in MongoDB

sample value in DB: one-two-three.js

Need to format like this: one two three

I split the field using $split aggregate, but after this how to replace "-" with " " ?

replaceAll("-", " ")

$push: {
  name: {$arrayElemAt:[{$split: ["$name" , "."]}, 0]},
}

Upvotes: 1

Views: 705

Answers (1)

turivishal
turivishal

Reputation: 36154

You can try,

  • your tried code, $set, $split name with . and get first element using $arrayElemAt
  • $reduce to iterate loop of name array after converting form string using $split
  • $concat to concat string with space and return value, this will return with extra space in first position of string, and $substr will remove that first position space
  {
    $set: {
      name: {
        $arrayElemAt: [{ $split: ["$file", "."] }, 0]
      }
    }
  },
  {
    $set: {
      name: {
        $substr: [
          {
            $reduce: {
              input: { $split: ["$name", "-"] },
              initialValue: "",
              in: { $concat: ["$$value", " ", "$$this"] }
            }
          },
          1,
          -1
        ]
      }
    }
  }

Playground

Upvotes: 1

Related Questions