def insert_many(self, dbname, collname, docs): """Inserts many documents into a database/collection.""" docs = [doc_cleanup(doc) for doc in docs] screened_docs = [] full_error = "" for doc in docs: valid, potential_error = validate_doc(collname, doc, self.rc) if not valid: screened_docs.append(doc) full_error += potential_error full_error += "\n" if len(screened_docs) != 0: print( "The following documents failed validation and were not uploaded\n" ) for doc in screened_docs: print(full_error) if doc in docs: docs.remove(doc) coll = self.client[dbname][collname] if ON_PYMONGO_V2: return coll.insert(docs) else: return coll.insert_many(docs)
def insert_one(self, dbname, collname, doc): """Inserts one document to a database/collection.""" doc = doc_cleanup(doc) valid, potential_error = validate_doc(collname, doc, self.rc) if not valid: raise ValueError(potential_error) coll = self.client[dbname][collname] if ON_PYMONGO_V2: i = coll.insert(doc) return InsertOneProxy(i, True) else: return coll.insert_one(doc)
def update_one(self, dbname, collname, filter, update, **kwargs): """Updates one document.""" filter['_id'].replace('.', '') doc = self.find_one(dbname, collname, filter) newdoc = dict(filter if doc is None else doc) newdoc.update(update) valid, potential_error = validate_doc(collname, newdoc, self.rc) if not valid: raise ValueError(potential_error) coll = self.client[dbname][collname] update = bson_cleanup(update) if ON_PYMONGO_V2: doc = coll.find_one(filter) if doc is None: if not kwargs.get("upsert", False): raise RuntimeError( "could not update non-existing document") newdoc = dict(filter) newdoc.update(update["$set"]) return self.insert_one(dbname, collname, newdoc) return coll.update(doc, update, **kwargs) else: return coll.find_one_and_update(filter, {"$set": update}, **kwargs)