如何获取_id MongoDB/php


How to get _id MongoDB/php?

我这样做:

$cursorLocations = $collection->find( array("locationName" => $locationName) )->limit(1);
if ($cursorLocations->count(true) == 1) {
    $idLocations = $cursorLocations->getNext();
    echo $idLocations["_id"];
}

如果这个问题一直存在,我会立即道歉,但阅读文档并没有找到答案。

也许还有其他方法可以获取_id?

在Mongo:中

db.collection.find({'field': 'value'}, {'_id' : 1});

在PHP中:

$cursorLocations = $collection->find( array("locationName" => $locationName), array('_id' => 1) )->limit(1);

上面的代码将限制您的查询仅检索_id字段,而不检索其他字段,您仍然需要从find()函数的结果中提取该字段的值-从$cursor对象中提取,如:

$_id = $cursorLoactions[`_id`];

还有一个MongoCursor方法key(),它返回当前的_id:

http://www.php.net/manual/en/mongocursor.key.php

所以你可以这样做:

$cursorLocations = $collection->find( array("locationName" => $locationName) )->limit(1);
$_id = $cursorLocations->key();