gpt4 book ai didi

javascript - MongoDB (php) - 将文档属性作为数组而不是多个属性返回

转载 作者:可可西里 更新时间:2023-11-01 09:56:37 26 4
gpt4 key购买 nike

我正在从 mongodb 数据库中读取文档并使用 php 将其传递给客户端。

文档包含一个数组属性。问题在于客户端将其作为具有名称 01 等属性的对象接收,而不是标准数组。

这是原始数据:

{ 
"_id" : ObjectId("573b47a1f99a8a1f9a6278a5"),
"persons" : [
{
"name" : "Moshe",
},
{
"name" : "E",
}, ...
]
}

根据要求,我附上了 var_export:

array (
0 =>
MongoDB\Model\BSONDocument::__set_state(array(
'_id' =>
MongoDB\BSON\ObjectID::__set_state(array(
)),
'persons' =>
MongoDB\Model\BSONArray::__set_state(array(
0 =>
MongoDB\Model\BSONDocument::__set_state(array(
'name' => 'Moshe',
)),
1 =>
MongoDB\Model\BSONDocument::__set_state(array(
'name' => 'E',
)),
)),
)),
)

和 var_dump:

array(1) {
[0]=>
object(MongoDB\Model\BSONDocument)#40 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#11 (1) {
["oid"]=>
string(24) "573b47a1f99a8d1f986278a5"
}
["persons"]=>
object(MongoDB\Model\BSONArray)#34 (1) {
["storage":"ArrayObject":private]=>
array(2) {
[0]=>
object(MongoDB\Model\BSONDocument)#10 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["name"]=>
string(5) "Moshe"
}
}
[1]=>
object(MongoDB\Model\BSONDocument)#12 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["name"]=>
string(1) "E"
}
}
}
}
}
}
}

这是 PHP 代码(全部):

function select(){
$conn = new MongoDB\Client("mongodb://localhost:27017");
$db = $conn->mydb;
$cursor = $db->entries_meta_data->find();
return current($cursor->toArray());
}

然后我使用像这样的 json_encode 将对象传递给客户端:

echo json_encode(select());

客户端显示的结果是:

{ 
"_id" : ObjectId("573b47a1f99a8a1f9a6278a5"),
"persons" : {
"0" : {
"name" : "Moshe",
},
"1" : {
"name" : "E",
}, ...
}
}

编辑:LordNeo居然解决了。阅读他的回答后,我将“选择”功能的最后一行更改为以下内容:

return json_decode(json_encode(current($cursor->toArray()),true);

它看起来很糟糕,但它确实有效。

我会非常高兴听到更好的解决方案。

最佳答案

原因是 new MongoDB driver处理 MongoDB 文档到不同于 the old driver 的 PHP 类型的转换.

好消息是您可以通过指定所谓的“类型映射”来获得旧行为。

文档有点隐藏,但你可以阅读它in the github repository of the driverin the online docs .

TL;DR 是你传递一个像这样的数组

array(
'array' => 'array',
'document' => 'array',
'root' => 'array'
)

作为 MongoDB\Client 的构造函数的第三个参数(“driverOptions”)或单独调用MongoDB\Driver\Cursor::setTypeMap()对于每个查询。

在你的例子中调用

$cursor->setTypeMap(array(
'array' => 'array',
'document' => 'array',
'root' => 'array'
));

$db->e​​ntries_meta_data->find() 之后应该可以解决问题。

关于javascript - MongoDB (php) - 将文档属性作为数组而不是多个属性返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37283350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com