Search code examples
stringmongodbtrim

remove whitespace which are in between String in Mongodb


For this document: { "_id" : 3, "name" : " Shyam Lingam " }

Expected: while retrieving _id = 3 then result should come like below:

{ "_id" : 3, "name" : "Shyam Lingam" }

I tried this: db.collection.find({_id:3},{name:{$trim:{input:"$name"}}})

{ "_id" : 3, "name" : "Shyam Lingam" }

but still whitespace between Shyam and Lingam is there which should not come.


Solution

  • This query may look complex.

    1. $trim - Trim the value of 1.1 at the beginning and end.

      1.1. $reduce - Transform array to string.

      1.1.1. input - Split name by space and filter the word which is not space.

      1.1.2. initialValue - Set the initial value as an empty string.

      1.1.3. in - With $concat, combine all the elements into a string with ' ' as the delimiter.

    db.collection.find({
      _id: 3
    },
    {
      name: {
        $trim: {
          input: {
            $reduce: {
              input: {
                $filter: {
                  input: {
                    $split: [
                      "$name",
                      " "
                    ]
                  },
                  cond: {
                    $ne: [
                      "$$this",
                      ""
                    ]
                  }
                }
              },
              initialValue: "",
              in: {
                $concat: [
                  "$$value",
                  " ",
                  "$$this"
                ]
              }
            }
          }
        }
      }
    })
    

    Demo @ Mongo Playground