MCPcopy Create free account
hub / github.com/Boris-code/feapder / add

Method add

feapder/db/mongodb.py:138–198  ·  view source on GitHub ↗

添加单条数据 Args: coll_name: 集合名 data: 单条数据 replace: 唯一索引冲突时直接覆盖旧数据,默认为False update_columns: 更新指定的列(如果数据唯一索引冲突,则更新指定字段,如 update_columns = ["name", "title"] update_columns_value: 指定更新的字段对应的值, 不指定则用数据本身的值更新 insert_igno

(
            self,
            coll_name,
            data: Dict,
            replace=False,
            update_columns=(),
            update_columns_value=(),
            insert_ignore=False,
    )

Source from the content-addressed store, hash-verified

136 return dataset
137
138 def add(
139 self,
140 coll_name,
141 data: Dict,
142 replace=False,
143 update_columns=(),
144 update_columns_value=(),
145 insert_ignore=False,
146 ):
147 """
148 添加单条数据
149 Args:
150 coll_name: 集合名
151 data: 单条数据
152 replace: 唯一索引冲突时直接覆盖旧数据,默认为False
153 update_columns: 更新指定的列(如果数据唯一索引冲突,则更新指定字段,如 update_columns = ["name", "title"]
154 update_columns_value: 指定更新的字段对应的值, 不指定则用数据本身的值更新
155 insert_ignore: 索引冲突是否忽略 默认False
156
157 Returns: 插入成功的行数
158
159 """
160 affect_count = 1
161 collection = self.get_collection(coll_name)
162 try:
163 collection.insert_one(data)
164 except DuplicateKeyError as e:
165 # 存在则更新
166 if update_columns:
167 if not isinstance(update_columns, (tuple, list)):
168 update_columns = [update_columns]
169
170 condition = self.__get_update_condition(
171 coll_name, data, e.details.get("errmsg")
172 )
173
174 # 更新指定的列
175 if update_columns_value:
176 # 使用指定的值更新
177 doc = {
178 key: value
179 for key, value in zip(update_columns, update_columns_value)
180 }
181 else:
182 # 使用数据本身的值更新
183 doc = {key: data[key] for key in update_columns}
184
185 collection.update_one(condition, {"$set": doc})
186
187 # 覆盖更新
188 elif replace:
189 condition = self.__get_update_condition(
190 coll_name, data, e.details.get("errmsg")
191 )
192 # 替换已存在的数据
193 collection.replace_one(condition, data)
194
195 elif not insert_ignore:

Callers

nothing calls this directly

Calls 4

get_collectionMethod · 0.95
zipFunction · 0.85
getMethod · 0.45

Tested by

no test coverage detected