mongo-中文字符的查询与插入

一、中文字符的查询 

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

 

posted @ 2012-11-02 15:56  醇酒醉影  阅读(9538)  评论(0编辑  收藏  举报