【发布时间】:2022-11-26 06:17:40
【问题描述】:
我正在尝试逻辑( insert if not exists , but if exists update the records )
我是 MongoDB 的新手,但我曾经使用 mysql 来做到这一点,是否可以使用 mongoDB 来实现这一点?
到目前为止,这是我的代码,它在 ( insert if not exists ) 的情况下运行良好,但在 ( update if exists ) 的情况下运行良好
$db = new MongoDB\Client($conn);
$collection = $db->auth->users;
$collection->createIndex(
array( "username" => 1 ),
array( "unique" => true )
);
$document = array(
"title" => "Mraaxs",
"fullname" => "John C12344",
"username" => "user1",
"age" => 22
);
$collection->updateOne(
array("username" => $document["username"]),
array('$setOnInsert' => $document),
array("upsert" => true)
);
【问题讨论】:
-
当前代码有什么问题?它会导致错误、文档重复、没有更改还是其他原因?