2

我有一个集合订阅者,它在 {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?

4

2 回答 2

2

这里的问题是它MongoCollection.update()不会返回一个_id(就像MongoCollection.insert()

如果数据库中没有匹配项并且您有upsert=>true,您将在对象id内部获得一个。upserted不是,如果有比赛

如果要更新或插入单个文档,可以使用findAndModify命令 with upsert(v.1.3.0-beta 中添加的助手)

$mongo = new Mongo();
$db = $m->mydatabase;
$query = array('LISTID' => 86, 'EMAIL' => 'opp20071980@gmail.com');
$update = array('$set' => array('LISTID' => 86, 'EMAIL' => 'opp20071980@gmail.com', 'FNAME' => 'Oleg') );

$result = $db->command(
  array(
    "findandmodify" => "test", / /name of collection
    "query" => $query,
    "update" => $update,
    'upsert' => 1
  )
);

两种情况下的结果会有所不同,请参见此处:

记录找到,更新:

Array
(
    [value] => Array
        (
            [_id] => MongoId Object
                (
                    [$id] => 506470963e20d69457000000
                )

            [LISTID] => 86
            [EMAIL] => opp20071980@gmail.com
        )

    [lastErrorObject] => Array
        (
            [updatedExisting] => 1
            [n] => 1
        )

    [ok] => 1
)

未找到记录,已插入:

Array
(
    [value] => 
    [lastErrorObject] => Array
        (
            [updatedExisting] => 
            [n] => 1
            [upserted] => MongoId Object
                (
                    [$id] => 5064708213995e82a829753e
                )

        )

    [ok] => 1
)

如果 findAndModify 插入或更新了文档,您必须_id在两个不同的地方获取。

于 2012-09-27T15:32:51.947 回答
0

更改$data变量并重$set试。

$data =  array('$set' => array('LISTID' => 86, 'EMAIL' => 'opp20071980@gmail.com', 'FNAME' => 'Oleg'));
于 2012-09-27T11:56:54.660 回答