我有一个集合订阅者,它在 {LISTID:1, EMAIL:1} 上有唯一索引。如果它不存在,我想插入一个文档,如果它已经存在则更新它,但无论如何我想获取文档的 _id,不管它是插入还是更新。
$mongo = new Mongo();
$db = $mongo->test;
$collection = $db->subscribers;
$criteria = array('LISTID' => 86, 'EMAIL' => 'opp20071980@gmail.com');
$data = array('LISTID' => 86, 'EMAIL' => 'opp20071980@gmail.com', 'FNAME' => 'Oleg');
$result = $collection->update($criteria, $data, array('fsync' => true, 'upsert' => true));
var_dump($data);
var_dump($result);
如果插入了文档,我会得到结果:
array
'LISTID' => int 86
'EMAIL' => string 'opp20071980@gmail.com' (length=21)
'FNAME' => string 'Oleg' (length=4)
array
'updatedExisting' => boolean false
'upserted' =>
object(MongoId)[6]
public '$id' => string '506446e4e0dae94a0bd25d06' (length=24)
'n' => int 1
'connectionId' => int 10
'fsyncFiles' => int 7
'err' => null
'ok' => float 1
但是如果它更新了,我会得到没有 _id 的结果:
array
'LISTID' => int 86
'EMAIL' => string 'opp20071980@gmail.com' (length=21)
'FNAME' => string 'Oleg' (length=4)
array
'updatedExisting' => boolean true
'n' => int 1
'connectionId' => int 10
'fsyncFiles' => int 7
'err' => null
'ok' => float 1
即使记录已更新但未插入,您能否告诉我如何获取 _id?