2013-03-12 88 views
1

我正在用mongodb和php进行项目。所以我试图找到使用它_id的记录。我在这里张贴的JSON值像这样如何使用mongodb _id查找记录

{"_id": {"$id": "513ea9d4a00b2ade09000001"}} 

然后我得到这个值,并对其进行解码,并用它来找到像这样

$obj = json_decode($json, true); 
$result = $collection->find($obj); 

但上面的代码给错误,因为在JSON他们是关键像$id。所以我如何解决上面的问题请帮助我。

回答

2

点直接从JSON字符串它是目前所有列出的例子略有不同我没有写一个详细的答案。

既然你现在有一个assoc命令阵列,它看起来像一个对象:

array(
    '_id' => array(
     '$id' => "513ea9d4a00b2ade09000001" 
    ) 
) 

您必须提取$id属性,并将其转换为MongoId像这样:

$db->collection->find(new MongoId($obj['$id'])); 

这将找到你的记录。

4

请按照下面的例子:

// This is only a string, this is NOT a MongoId 
$mongoid = '4cb4ab6d7addf98506010000'; 

// You will not find anything by searching by string alone 
$nothing = $collection->find(array('_id' => $mongoid)); 
echo $nothing->count(); // This should echo 0 

// THIS is how you find something by MongoId 
$realmongoid = new MongoId($mongoid); 

// Pass the actual instance of the MongoId object to the query 
$something = $collection->find(array('_id' => $realmongoid)); 
echo $something->count(); // This should echo 1 

你可以找到更多信息here

1

要使用'_id'查找文档,您必须将其转换为MongoId对象。这可以通过在find查询中传递array('_id' => new MongoId($valOf_id))来完成。

,因为我相信这是足以让你得到:-)