MongoDB特殊字符

时间:2015-07-09 19:51:21

标签: mongodb spring-data special-characters string-formatting utf

我已将一个init文件插入MongoDB:

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可以做些什么?

2 个答案:

答案 0 :(得分:7)

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编码的,甚至是用户提交的字符串。

答案 1 :(得分:4)

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

<强>代码

您可以使用&amp; ouml; 将spl char保存在db中。

db.User.insert({ "_id" : ObjectId("5589929b887dc1fdb501cdba"), "_class" : "com.smartinnotec.aposoft.dao.domain.User", "title" : "DI.", ... "address" : { "_id" : null, ... "country" : "&ouml;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

Replace multiple characters in a string in javascript

希望这有帮助。

相关问题