skip to Main Content

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.

2

Answers


  1. 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

    Login or Signup to reply.
  2. Try this i hope it should be work

    db.collection.update(
      { "_id": 3 },
      { "$set": { "name": { "$trim": { "input": "$name" } } } }
    )
    

    After update output is:

    { "_id" : 3, "name" : "Shyam Lingam" }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search