Home > front end >  trim existing value in mongo documents
trim existing value in mongo documents

Time:11-26

I currently have some DB in mongoose that has some values that were not trim() initially but now I want to trim all the values. How do I find and trim all the values. Below is an example of the DB and the expected result.

DB:

[
  {
    "key": "hello "
  },
  {
    "key": "world"
  },
  {
    "key": "test "
  }
]

expected result:

[
  {
    "key": "hello"
  },
  {
    "key": "world"
  },
  {
    "key": "test"
  }
]

CodePudding user response:

You can use $trim since is possible to use aggregation stages into the update query.

db.collection.updateMany({},
[
  {
    "$set": {
      "key": {
        "$trim": {
          "input": "$key"
        }
      }
    }
  }
])

Example here

Also to do it more efficient you can trim only values which finish with a space using a regular expresion like this example. I'm not an expert on regex but "^.* $" should match only values with a space at the end.

  • Related