gotask icon indicating copy to clipboard operation
gotask copied to clipboard

mongo_client批量插入的时候部分_id重复无法获取实际插入的数量

Open axpwx opened this issue 3 years ago • 0 comments

伪代码:

<?php
$insertMany = [
  { _id: 1, qty: 20 },
  { _id: 2, qty: 55 },
  { _id: 2, qty: 30 },
  { _id: 3, qty: 100},
  { _id: 3, qty: 120},
  { _id: 4, qty: 20},
  { _id: 5, qty: 30}
];
try {
  $insertResult = $mongoTable->insertMany($insertMany, ['ordered' => false]);
  printf("Inserted %d document(s)\n", count($insertResult->getInsertedIDs()));
} catch (ServiceException $e) {
  print_r($e->getMessage());
  //output like: error 'error while executing mongo command: bulk write error: [{[{E11000 duplicate key error collection: db_aaa.t_table index: _id_ dup key: { _id: "2"}} {E11000 duplicate key error collection: db_aaa.t_table index: _id_ dup key: { _id: "3" }}]}, {<nil>}]' on 'Hyperf\GoTask\Relay\CoroutineSocketRelay'
} catch (GoridgeException $e) {
  //other logic
}

ordered是false的时候,会继续插入非重复的数据,但是ServiceException没有提供实际写入的数据,可靠性不好控制。

axpwx avatar Apr 01 '22 13:04 axpwx