使用PHP插入后获取MongoID

时间:2013-08-28 06:34:52

标签: php mongodb insert

我正在使用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 

5 个答案:

答案 0 :(得分:1)

我是按照以下方式进行的

$IDm = new MongoId();

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

$collection->insert($data_object);

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

答案 1 :(得分:1)

除非您在原始帖子中没有共享某些代码,否则$data_object_id在您调用__toString()时没有理由应该是stdClass的实例。如果你粘贴一个复制问题的整个脚本而不是单行讨论它们会更有帮助。

您写道:

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的{​​{3}} / type或检查__toString() class是否能够诊断出来。

考虑以下脚本:

<?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

答案 2 :(得分:0)

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

$data_object_id = (string) $data_object['_id'];

答案 3 :(得分:0)

试试这个

$data= iterator_to_array($data_object_id);
 print_r($data);

答案 4 :(得分:0)

使用新的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'}