问题 MongoDB特殊字符


我在MongoDB中插入了一个init文件:

db.User.insert({ "_id" : ObjectId("5589929b887dc1fdb501cdba"), "_class" : "com.smartinnotec.aposoft.dao.domain.User", "title" : "DI.", ... "address" : { "_id" : null, ... "country" : "Österreich" }})

如果我使用db.User.find()调用此条目,则会得到以下内容:

{ "_id" : ObjectId("5589929b887dc1fdb501cdba"), "_class" : "com.smartinnotec.aposoft.dao.domain.User", "title" : "DI.", ... "address" : { "_id" : null, ... "country" : "�sterreich" } }

带有特殊字符的单词“�sterreich不正确。

有没有人知道我可以在mongodb做什么来解决这个问题?


2704
2017-07-09 19:51


起源

您使用的是什么版本的mongodb? - Alex
db.version()3.0.7 - quma
你从mongo控制台得到这个结果吗? - Rabea
我也使用v3.0.7。我尝试你的代码没有任何奇怪的情况。我想和Rabee一起问同样的问题; “你是从mongo控制台得到这个结果吗?”。因为MongoDB将数据以BSON格式存储为UTF8编码。在发送到MongoDB之前,可能会立即发生更改。祝你好运.. - efkan
要将结果打印到的控制台正在尝试表示单字节字符(UTF-8) UTF-16 或其他一些多字节字符集。您需要更改控制台设置以显示字符 UTF-8 格式。 - BatScream


答案:


猜猜你可以在字符串中使用HTML代码

您可以使用 ö 在db中保存spl char。

db.User.insert({ "_id" : ObjectId("5589929b887dc1fdb501cdba"), "_class" : "com.smartinnotec.aposoft.dao.domain.User", "title" : "DI.", ... "address" : { "_id" : null, ... "country" : "österreich" }})

在使用db.User.find()调用此条目时,您将获得以下内容:

{ "_id" : ObjectId("5589929b887dc1fdb501cdba"), "_class" : "com.smartinnotec.aposoft.dao.domain.User", "title" : "DI.", ... "address" : { "_id" : null, ... "country" : "Österreich" } }

参考

http://www.starr.net/is/type/htmlcodes.html

在javascript中替换字符串中的多个字符

希望这可以帮助。


4
2017-12-15 06:22





JSON和BSON只能编码/解码有效的UTF-8字符串,如果您的数据(包含的输入)不是UTF-8,您需要在将其传递给任何JSON相关系统之前对其进行转换,如下所示:

$string = iconv('UTF-8', 'UTF-8//IGNORE', $string); // or
$string = iconv('UTF-8', 'UTF-8//TRANSLIT', $string); // or even
$string = iconv('UTF-8', 'UTF-8//TRANSLIT//IGNORE', $string); // not sure how this behaves

我个人更喜欢第一个选项,请参阅 iconv() 手册页。其他选择包括:

mb_convert_encoding(“Österreich”,“UTF-8”,“ISO-8859-1”);

  • utf8_encode(utf8_decode($string))

您应该始终确保您的字符串是UTF-8编码的,甚至是用户提交的字符串。


7
2017-12-15 09:55