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
This query may look complex.
$trim
– Trim the value of 1.1 at the beginning and end.1.1.
$reduce
– Transform array to string.1.1.1.
input
– Splitname
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.Demo @ Mongo Playground
Try this i hope it should be work
After update output is: