如何在mongodb数据库中存储特殊字符


How store special characters in mongodb database?

我已经安装了mongodb 2.4.5版本,并且可以正常使用linux CENTOS,但在尝试插入特殊字符时遇到了问题,下面是一个示例。

使用PHP,我做了以下操作。。。

$con = new MongoClient(); //connect
$db = $con->selectDB('test');
$dbs = $db->titles; //Set to titles collection
$dbs->insert(array('name' => 'televisión')); //Inserts the item into the titles collection

但在mongodb中,数据库服务器保存如下

> db.titles.find()
{ "name" : "televisi��n" }

我想知道是否有任何方法可以将带有特殊字符的数据存储到数据库中,即{ "name" : "televisión" }

提前感谢

基于mb_detect_encoding(),"televisión"看起来是一个UTF-8字符串,所以在MongoDB中存储它应该不会有任何问题。事实上,我能够从PHP和JavaScriptshell将它作为键和值插入数据库。

你能插入文档并使用PHP检索它吗?您的示例只显示了插入步骤。考虑以下脚本:

$name = 'televisión';
$m = new MongoClient();
$c = $m->test->titles;
$c->insert(['name' => $name]);
var_dump($c->findOne(['name' => $name]));

这个脚本在我的系统上打印以下内容:

array(2) {
  '_id' =>
  class MongoId#6 (1) {
    public $$id =>
    string(24) "5213c3dbe84df10121873458"
  }
  'name' =>
  string(11) "televisión"
}

此外,我可以在JavaScript外壳中查询相同的文档:

> db.titles.find({name: "televisión"})
{ "_id" : ObjectId("5213c3dbe84df10121873458"), "name" : "televisión" }

您的终端可能只是在显示UTF-8字符时出现问题。

我刚刚在使用拉丁字符(çãóõé…)时遇到了同样的问题,但使用了Node.js。以下是我解决这个问题的方法:

JavascriptString.toString("utf8");