我有一个收集订阅者,它在{LISTID:1,EMAIL:1}上具有唯一索引。 我想插入一个文件,如果它不存在,并更新它,如果已经存在,但在任何情况下,我想获取文档的_id无关紧要,如果它插入或更新。获取我们插入的mongodb文档的_id,如果它不存在并更新(如果它已经存在)
$mongo = new Mongo();
$db = $mongo->test;
$collection = $db->subscribers;
$criteria = array('LISTID' => 86, 'EMAIL' => '[email protected]');
$data = array('LISTID' => 86, 'EMAIL' => '[email protected]', 'FNAME' => 'Oleg');
$result = $collection->update($criteria, $data, array('fsync' => true, 'upsert' => true));
var_dump($data);
var_dump($result);
如果文档被插入,我得到的结果是:
array
'LISTID' => int 86
'EMAIL' => string '[email protected]' (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 '[email protected]' (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即使记录更新,但没有插入?
谢谢。我会试试看。 – Oleg
在我看来,它的工作原理。 – Oleg