-->

MongoDB query to capitalise first letter in existi

2019-03-06 17:00发布

问题:

Here is the problem,

I want to capitalise the first letter of a name in my existing database, just wanted to know if there is any query so that i can make it possbile.

what i want -- in my database so many names is in unformatted ways.. like lucy, Sean, jon and so on. i want to make them in a formatted ways like. Lucy. Sean, Jon. Can anyone help me with this?

Thanks in advance.

回答1:

it may not be the best solution. the only hiccup in below suggestion is to get "3" of $substr:["$name1",1,3] dynamically. but gives you a start?

db.toupper.aggregate([{$project:{name:{$concat:[{$toUpper:{$substr:["$name1",0,1]}},{$substr:["$name1",1,**3**]}]}}}])

below is the result

 db.toupper.find()

 "_id" : ObjectId("5767ca0badb381a5cc0d19cd"), "name1" : "lean" }
 "_id" : ObjectId("5767ca3aadb381a5cc0d19ce"), "name1" : "lean" }

 db.toupper.aggregate([{$project:{name:{$concat:[{$toUpper:{$substr:["$name1",0,1]}},{$substr:["$name1",1,3]}]}}}])

 "_id" : ObjectId("5767ca0badb381a5cc0d19cd"), "name" : "Lean" }
 "_id" : ObjectId("5767ca3aadb381a5cc0d19ce"), "name" : "Lean" }