11

查询后是否可以获得新的/更新的_id?示例代码:

$key = array( 'something' => 'unique' );
$data = array( '$inc' => array( 'someint' => 1 ) );
$mongodb->db->collection->update( $key, $data, array( 'upsert' => true ) );

$key 没有持有新/旧 _id 对象,我认为 $data 也不会,因为它只是一条指令。

4

6 回答 6

16

是 - 可以使用单个查询。

MongoDB 包含一个findAndModify可以原子地修改文档并返回它的命令(默认情况下,它实际上是在修改之前返回文档)。

PHP 驱动程序在集合类上没有为此提供方便的方法(但是——查看这个错误),但它仍然可以使用(注意我的 PHP 很糟糕,所以我很可能犯了语法错误在以下代码段中):

$key = array( 'something' => 'unique' );
$data = array( '$inc' => array( 'someint' => 1 ) );
$result = $mongodb->db->command( array(
    'findAndModify' => 'collection',
    'query' => $key,
    'update' => $data,
    'new' => true,        # To get back the document after the upsert
    'upsert' => true,
    'fields' => array( '_id' => 1 )   # Only return _id field
) );
$id = $result['value']['_id'];
于 2010-12-13T23:30:23.347 回答
15

万一有人像我一样偶然发现这个问题,当您调用 MongoCollection->save(); 时,Mongo 实际上会修改输入数组;- 将 id 附加到末尾。所以,如果你打电话:

$test = array('test'=>'testing');
mongocollection->save($test);
echo $test['_id'];

您将拥有该对象的 mongo id。

于 2011-01-27T04:58:42.090 回答
3

我遇到了这个问题,并通过在 upsert 之后查询 _id 来解决它。我想我会添加一些我的发现,以防它们对任何来这里搜索信息的人有用。

当 upsert 导致在集合中创建一个新文档时,返回的对象包含 _id(这里是一个示例的 print_r):

Array

(

[updatedExisting] => 0

[upserted] => MongoId Object
    (
        [$id] => 506dc50614c11c6ebdbc39bc
    )

[n] => 1
[connectionId] => 275
[fsyncFiles] => 7
[err] => 
[ok] => 1
)

您可以从中获取 _id:

$id = (string)$obj['upserted'];

但是,如果 upsert 导致现有文档被更新,则返回的对象不包含 _id。

于 2012-10-04T17:56:41.047 回答
1

试一试:

function save($data, $id = null) {
    $mongo_id = new MongoId($id);
    $criteria = array('_id' => $mongo_id);
    // Wrap a '$set' around the passed data array for convenience
    $update = array('$set' => $data);
    $collection->update($criteria, $update, array('upsert' => true));
}

所以让我们说传递$id的是空的,一个新MongoId的被创建,否则它只是将现有的转换$id为一个 MongoId 对象。

希望这会有所帮助:D

于 2013-04-16T12:10:50.733 回答
1

update 方法返回一个数组,其中包含文档 UPSERTED 的 ID:

Array
(
    [ok] => 1
    [nModified] => 0
    [n] => 1
    [err] => 
    [errmsg] => 
    [upserted] => MongoId Object
        (
            [$id] => 5511da18c8318aa1701881dd
        )
    [updatedExisting] => 
)
于 2015-03-24T22:13:49.113 回答
0

您还可以在更新/更新插入中将 fsync 设置为 true,以将 _id 返回到已传递给更新的对象。

$save = array ('test' => 'work');
$m->$collection->update(criteria, $save, array('fsync' => true, 'upsert' => true));
echo $save['_id']; //should have your _id of the obj just updated.
于 2012-06-21T07:17:56.700 回答