用php upsert后获得mongodb _id对象 [英] get mongodb _id object after upsert with php

查看:55
本文介绍了用php upsert后获得mongodb _id对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

is it possible to get the new/updated _id after the query? example code:

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

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

$key is not holding the new/old _id object and i assume that $data will not either because its just an instruction.

推荐答案

是-可以使用单个查询.

MongoDB包括一个 findAndModify 命令,该命令可以自动修改文档并返回(默认情况下)它实际上会在修改文档之前返回该文档.)

MongoDB includes a findAndModify command that can atomically modify a document and return it (by default it actually returns the document before it's been modified).

PHP驱动程序尚未在集合类中包括用于此目的的便捷方法(但请查看此错误),但仍然可以使用(请注意,我的PHP很糟糕,因此我很可能在以下代码段中出现了语法错误):

The PHP drivers don't include a convenient method for this on the collection class (yet -- check out this bug), but it can still be used (note that my PHP is terrible, so I may very well have made a syntax error in the following snippet):

$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'];

这篇关于用php upsert后获得mongodb _id对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆