MongoDB & PHP - 处理重复文档



我有一个集合,我想限制具有特定字段的文档的重复。按照这个SO线程的指导,我手动实现了一个索引:

{
"playerName": 1,
"comp.compName": 1,
"comp.roundNo": 1
},
{
"unique": true
}

现在,当我尝试插入一个会导致重复的新文档时,PHP页面/脚本错误为:

致命错误:未捕获MongoDB \Driver\Exception \BulkWriteException:E11000重复密钥错误集合:golf.round索引:playerName_1_comp.name_1_comp.roundNo_1重复密钥:{playerName:"ErnieEls";,comp.name:";2021年美国网球公开赛";,comp.roundNo:3}英寸/usr/bin/vvendor/mongodb/mongodb/src/Operation/InsertOne.php:134堆栈跟踪:#0/usr/bin/vvendor/mongodb/mongodb/src/Operation/InsertOne.php(134(:MongoDB \驱动程序\服务器->executeBulkWrite('gof.round',对象(MongoDB \ Driver \ BulkWrite(,数组(#1/usr/bin/vender/mongodb/mongodb/src/Collection.php(931(:MongoDB \操作\插入一->execute(对象(MongoDB \Driver\Server((#2/var/www/html/selectComp.php(90(:MongoDB \集合->insertOne(数组(#3{main}在/usr/bin/vvendor/mongodb/mongodb/src/Operation/InsertOne.php中抛出134

要获得插入的所有数据字段,我需要循环遍历另一个comp集合查询的结果,其中子查询包含到round嵌入对象中。当完全完成时,它还应该需要查询所选的player数据(可能是用户登录功能,但尽量避免!(:

$insertOneResult = $collectionRound->insertOne(
[
'playerName' => "Ernie Els", //$_COOKIE['playerName'],
'playerId' => "a1b2c3", //$_COOKIE['playerId'],
'date' => new MongoDBBSONUTCDateTime(strtotime("today")*1000),
'comp' => [
'id' => $comp['_id'],
'name' => $comp['compName'],
'tees' => $newScore['courseTee'],
'roundNo' => $round['roundNo'],
'scoringMethod' => $comp['compScoringMethod']
],
'hcap' => 0, //$_COOKIE['playerHcap'],
'holeCount' => 9, // from course or comp?
'computedScore' => 0,
'computedThru' => 0,
'holes' => [],
'team' => "PGA Tour", //$_COOKIE['playerTeam'],
'countbackScores' => []
]
);

如何处理此错误?我的意图只是简单地限制添加重复项,而忽略此请求。根据使用情况,这可能会通知用户或被忽略。

为什么在插入文档时不使用trycatch异常处理。当出现重复时,它会向您抛出一个错误,您可以在catch块中捕获exception而不执行任何操作。

试试这个:

try{
$insertOneResult = $collectionRound->insertOne(
[
'playerName' => "Ernie Els", //$_COOKIE['playerName'],
'playerId' => "a1b2c3", //$_COOKIE['playerId'],
'date' => new MongoDBBSONUTCDateTime(strtotime("today")*1000),
'comp' => [
'id' => $comp['_id'],
'name' => $comp['compName'],
'tees' => $newScore['courseTee'],
'roundNo' => $round['roundNo'],
'scoringMethod' => $comp['compScoringMethod']
],
'hcap' => 0, //$_COOKIE['playerHcap'],
'holeCount' => 9, // from course or comp?
'computedScore' => 0,
'computedThru' => 0,
'holes' => [],
'team' => "PGA Tour", //$_COOKIE['playerTeam'],
'countbackScores' => []
]
);
}
catch(Exception $e){
// This block will catch the duplicate exception
// Dont do anything here, and just ignore the request
echo 'Error message: ' .$e->getMessage();
}

备用:您可以首先使用.find()查找条目是否存在,如果存在,请不要插入文档并忽略请求。

最新更新