gpt4 book ai didi

php - 如果不存在则获取我们插入的 mongodb 文档的 _id,如果它已经存在则更新

转载 作者:可可西里 更新时间:2023-11-01 10:34:08 27 4
gpt4 key购买 nike

我有一个在 {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 吗?

最佳答案

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

如果数据库中没有匹配,而您的upsert=>true,您将在中得到一个id >upserted 对象。如果匹配,则不会。

如果要更新或插入单个文档,可以使用 findAndModify 命令和 upsert(v.1.3 中添加的帮助程序.0-测试版)

$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
)

您必须在两个不同的地方获取 _id,具体取决于 findAndModify 是插入还是更新文档。

关于php - 如果不存在则获取我们插入的 mongodb 文档的 _id,如果它已经存在则更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12620392/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com