Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"}}})

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{ "_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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading