0

如果我在集合中用自身替换文档,则文档似乎已更改。由于这个问题,我的数据变得无法使用。我究竟做错了什么?

<?php

$login = '***removed***';
$pass = '***removed***';
$schema_name = 'dev';
$collection_name = 'test';

$session    = mysql_xdevapi\getSession("mysqlx://$login:$pass@localhost");
$schema     = $session->getSchema($schema_name);
$collection = $schema->getCollection($collection_name);

// Delete all documents in the collection.
$collection->remove('true')->execute();

// Add one document and get its ID.
$result = $collection->add('{ "accent": "\u00e8" }')->execute();
$ids = $result->getGeneratedIds();
$doc_id = $ids[0];

// Read the document from the database.
$row = $collection->getOne($doc_id);
print "1st getOne() : " . $row['accent'] . "\n";

// Replace the document with itself.
$collection->replaceOne($doc_id, $row);

// Read the document from the database again.
$row = $collection->getOne($doc_id);
print "2nd getOne() : " . $row['accent'] . "\n";

// One more time.
$collection->replaceOne($doc_id, $row);

$row = $collection->getOne($doc_id);
print "3rd getOne() : " . $row['accent'] . "\n";

?>

上述脚本的输出:

$ php test.php 
1st getOne() : è
2nd getOne() : \u00e8
3rd getOne() : \\u00e8

我正在使用 PHP v7.3.19 和 mysql_xdevapi v8.0.22。

4

1 回答 1

0

可能是转换问题。正如您在文档中看到的, add 和 replaceOne 方法接受集合对象或 JSON 文档:

https://www.php.net/manual/en/mysql-xdevapi-collection.add.php https://www.php.net/manual/en/mysql-xdevapi-collection.replaceone.php

在您的示例中,您在 add 方法中使用 JSON 文档,但是当您使用 getOne 方法检索该文档时,结果是一个集合对象:https://www.php.net/manual/en/mysql-xdevapi-collection。 getone.php

最后,当您尝试更新它时,您会使用之前生成的集合对象,并且集合对象和 JSON 对象的行为不同。

为了实现你想要的,我建议你使用集合对象而不是 JSON 对象创建第一个注册表,这应该避免在检索数据时出现字符集或转换问题。好看!

示例:['accent' => '\u00e8']

于 2020-12-20T04:02:08.700 回答