批量添加数据 Args: coll_name: 集合名 datas: 数据 [{'_id': 'xx'}, ... ] replace: 唯一索引冲突时直接覆盖旧数据,默认为False update_columns: 更新指定的列(如果数据的唯一索引存在,则更新指定字段,如 update_columns = ["name", "title"] update_columns_value: 指定更新的字段对应的值, 不指定则用数据本身的值更新
(
self,
coll_name: str,
datas: List[Dict],
replace=False,
update_columns=(),
update_columns_value=(),
condition_fields: dict = None,
)
| 198 | return affect_count |
| 199 | |
| 200 | def add_batch( |
| 201 | self, |
| 202 | coll_name: str, |
| 203 | datas: List[Dict], |
| 204 | replace=False, |
| 205 | update_columns=(), |
| 206 | update_columns_value=(), |
| 207 | condition_fields: dict = None, |
| 208 | ): |
| 209 | """ |
| 210 | 批量添加数据 |
| 211 | Args: |
| 212 | coll_name: 集合名 |
| 213 | datas: 数据 [{'_id': 'xx'}, ... ] |
| 214 | replace: 唯一索引冲突时直接覆盖旧数据,默认为False |
| 215 | update_columns: 更新指定的列(如果数据的唯一索引存在,则更新指定字段,如 update_columns = ["name", "title"] |
| 216 | update_columns_value: 指定更新的字段对应的值, 不指定则用数据本身的值更新 |
| 217 | condition_fields: 用于条件查找的字段,不指定则用索引冲突中的字段查找 |
| 218 | |
| 219 | Returns: 添加行数,不包含更新 |
| 220 | |
| 221 | """ |
| 222 | add_count = 0 |
| 223 | |
| 224 | if not datas: |
| 225 | return add_count |
| 226 | |
| 227 | collection = self.get_collection(coll_name) |
| 228 | if not isinstance(update_columns, (tuple, list)): |
| 229 | update_columns = [update_columns] |
| 230 | |
| 231 | try: |
| 232 | add_count = len(datas) |
| 233 | collection.insert_many(datas, ordered=False) |
| 234 | except BulkWriteError as e: |
| 235 | write_errors = e.details.get("writeErrors") |
| 236 | for error in write_errors: |
| 237 | if error.get("code") == 11000: |
| 238 | # 数据重复 |
| 239 | # 获取重复的数据 |
| 240 | data = error.get("op") |
| 241 | |
| 242 | def get_condition(): |
| 243 | # 获取更新条件 |
| 244 | if condition_fields: |
| 245 | condition = { |
| 246 | condition_field: data[condition_field] |
| 247 | for condition_field in condition_fields |
| 248 | } |
| 249 | else: |
| 250 | # 根据重复的值获取更新条件 |
| 251 | condition = self.__get_update_condition( |
| 252 | coll_name, data, error.get("errmsg") |
| 253 | ) |
| 254 | |
| 255 | return condition |
| 256 | |
| 257 | if update_columns: |
nothing calls this directly
no test coverage detected