avolquez
avolquez

Reputation: 753

How store special characters in mongodb database?

I have mongodb 2.4.5 version installed and working properly with linux CENTOS, but I have a problem when I try to insert special characters, below an example.

Using PHP I did the following ...

$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

But in mongodb database server is saved as follows

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

I wonder if there are any way to store the data with the special character into the database, i.e { "name" : "televisión" }

Thanks in advance

Upvotes: 0

Views: 7179

Answers (2)

Léo Muniz
Léo Muniz

Reputation: 627

I just faced the same problem with latin characters (ç ã ó õ é...) but using Node.js. Here is how I solved this:

JavascriptString.toString("utf8");

Upvotes: 0

jmikola
jmikola

Reputation: 6922

Based on mb_detect_encoding(), "televisión" appears to be a UTF-8 string, so you should not have any problem storing it in MongoDB. Indeed, I was able to insert it as both a key and a value into the database, from both PHP and the JavaScript shell.

Are you able to insert the document and retrieve it using PHP? Your example only showed the insertion step. Consider the following script:

$name = 'televisión';

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

This script prints the following on my system:

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

Additionally, I'm able to query for the same document in the JavaScript shell:

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

It's possible that your terminal is simply having trouble displaying UTF-8 characters.

Upvotes: 1

Related Questions