一、中文字符的查詢
在windows的cmd命令中,查詢mongo數據時,中文會出現亂碼:
C:\>mongo 127.0.0.1:2222/test
MongoDB shell version: 1.8.3
connecting to: 127.0.0.1:2222/test
neu:PRIMARY> show collections
system.indexes
t1
yctshard
neu:PRIMARY> db.t1.find()
{ "_id" : ObjectId("50937174e513bab18cd6d3cb"), "name" : "a" }
{ "_id" : ObjectId("509371a20e772f000d809886"), "name" : "a" }
{ "_id" : ObjectId("509371cf3b76c05fa4cc5f00"), "name" : "鐢版湀瓚? }
{ "_id" : ObjectId("509372883d5e7033c902550c"), "name" : "鐢版湀瓚?" }
{ "_id" : ObjectId("509372883d5e7033c902550d"), "name" : "鐢版湀瓚?" }
neu:PRIMARY>
這是因為mongo中的字符以utf-8格式存儲,而cmd默認為GBK(936)格式。可以將你當前的cmd窗口改為utf8()
1. 設置當前cmd窗口為utf8格式:
neu:PRIMARY> ^Z
bye
C:\>chcp 65001
在新打開的cmd窗口標題上點右鍵 - “屬性” - “字體”,將字體改為非“點陣字體”,然后再重新登錄並查詢,你就能看到正常的中文了:
C:\>mongo 127.0.0.1:2222/test
MongoDB shell version: 1.8.3
connecting to: 127.0.0.1:2222/test
neu:PRIMARY> db.t1.find()
{ "_id" : ObjectId("50937174e513bab18cd6d3cb"), "name" : "a" }
{ "_id" : ObjectId("509371a20e772f000d809886"), "name" : "a" }
{ "_id" : ObjectId("509371cf3b76c05fa4cc5f00"), "name" : "田田田" }
{ "_id" : ObjectId("509372883d5e7033c902550c"), "name" : "田田田1" }
{ "_id" : ObjectId("509372883d5e7033c902550d"), "name" : "田田田2" }
二、中文字符的插入
當在cmd中批量插入記錄時,若有中文,則同樣會提示錯誤:
C:\>mongo 127.0.0.1:2222/test
MongoDB shell version: 1.8.3
connecting to: 127.0.0.1:2222/test
neu:PRIMARY> db.t3.find()
neu:PRIMARY>
neu:PRIMARY> db.t3.insert(name:"田")
Fri Nov 02 15:45:26 malformed UTF-8 character sequence at offset 19
此時,可以通過mongo的--shell參數執行該插入語句。
neu:PRIMARY> ^Z
bye
C:\>echo db.t3.insert({name:"田"}) > yct.txt
C:\>cat yct.txt
db.t3.insert({name:"田"})
將yct.txt轉成utf8格式的文本后,通過mongo的shell參數執行該文件即可:
C:\>mongo 127.0.0.1:2222/test --shell c:\yct.txt
MongoDB shell version: 1.8.3
connecting to: 127.0.0.1:2222/test
type "help" for help
neu:PRIMARY> db.t3.find()
{ "_id" : ObjectId("50937b13d9f693e860cc327d"), "name" : "鐢? }
neu:PRIMARY>
這里的中文顯示亂碼,可以通過剛才介紹的方法解決。
另:若有多條記錄,在文本中使用回車換行符分隔即可:
C:\>cat yct.txt
db.t3.insert({name:"田"})
db.t3.insert({name:"田1"})
db.t3.insert({name:"田2"})
