2

我正在使用PHP官方的 Mongo 驱动程序并进行插入。

$collection->insert($data_object);

然后做:

$data_object_id = $data_object['_id'];

如果我这样做:

print_r($data_object_id);

看起来不错:

 MongoId Object
 (
     [$id] => 521d982298a618b9798b456b
 )

但是,当尝试这样做时:

 echo "Inserted: " . $data_object_id->__toString() . "...";

我收到以下错误:

 Catchable fatal error: Object of class stdClass could not be converted to string 
4

5 回答 5

1

没有理由$data_object_id在您调用时应该是 stdClass 的实例__toString(),除非您在原始帖子中未共享某些代码。如果您粘贴整个脚本来重现您的问题,而不是在它们之间进行讨论的单行,这将更有帮助。

你写了:

echo "Inserted: " . $data_object_id->__toString() . "...";`

我收到以下错误:

Catchable fatal error: Object of class stdClass could not be converted to string`

如果$data_object_id是 stdClass 实例,则该echo行将导致以下错误:

Fatal error: Call to undefined method stdClass::__toString()

您应该能够简单地通过检查类型/$data_object_id或检查其上是否__toString() 存在该方法来诊断此问题。

考虑以下脚本:

<?php

$m = new MongoClient();
$c = $m->test->foo;

$doc = (object) ['x' => 1];
$c->insert($doc);
printf("Document is: %s\n", get_class($doc));
printf("_id field is: %s\n", get_class($doc->_id));
printf("_id cast to string: %s\n", (string) $doc->_id);
printf("_id toString(): %s\n", $doc->_id->__toString());

echo "\n";

$doc = ['x' => 2];
$c->insert($doc);
printf("Document is: %s\n", gettype($doc));
printf("_id field is: %s\n", get_class($doc['_id']));
printf("_id cast to string: %s\n", (string) $doc['_id']);
printf("_id toString(): %s\n", $doc['_id']->__toString());

这将插入一个单字段文档,测试对象和数组形式,并打印有关_id在调用insert(). 这应该会产生以下输出(当然,ObjectId 哈希值会有所不同):

Document is: stdClass
_id field is: MongoId
_id cast to string: 5220ad40e84df1b667000000
_id toString(): 5220ad40e84df1b667000000

Document is: array
_id field is: MongoId
_id cast to string: 5220ad40e84df1b667000001
_id toString(): 5220ad40e84df1b667000001
于 2013-08-30T14:40:08.217 回答
1

我正在按照以下方式进行操作

$IDm = new MongoId();

$data_object = array(
  '_id' => $IDm,
  ...    // all other things that you need
) 

$collection->insert($data_object);

稍后您可以执行类似 echo$IDm->{'$id'}的操作以将 ID 作为字符串提供

于 2013-08-28T13:10:19.787 回答
0

您是否尝试过投射 MongoId 对象?

$data_object_id = (string) $data_object['_id'];
于 2013-08-28T06:40:55.437 回答
0

尝试这个

$data= iterator_to_array($data_object_id);
 print_r($data);
于 2014-12-30T10:25:21.967 回答
0

使用 new mongoId() 创建变量并将其推送到您的对象

$id = new MongoId();
$data_object = array(
 "_id"       => $id,
 "moreData" => "someData"
);
try {
    $collection->insert($data_object);
    return $id;
} catch(MongoException $e) {
    echo $e;
}

回显 id 字符串

echo $id->{'$id'}
于 2015-08-27T08:26:54.563 回答