def get(self, id): d = self.c.find_one({"id": id}) if d: return dictToObject(d, self.clz()) else: # TODO: logger return None
def query(self, filter={}, offset=0, limit=100, sort=[]): ss = [] for s in sort: if isinstance(s, types.DictionaryType): for k, v in s.items(): ss.append((k, v)) else: ss.append(s) sort = ss if len(sort) == 0: sort = [("id", -1)] if "isValid" not in filter.keys(): filter["isValid"] = True cursor = self.c.find(filter=filter, skip=offset, limit=limit, sort=sort) r = dict() r["total"] = cursor.count() r["offset"] = offset sets = [] for c in cursor: sets.append(dictToObject(c, self.clz())) r["result"] = sets if r["total"] <= r["offset"]: r["result"] = [] return r
def update(self, entity): d = objectToDict(entity) getMongoHelper().set_doc_update_time(d) d["isValid"] = True d = self.c.find_one_and_update({"id": entity.id}, {"$set": d}, return_document=ReturnDocument.AFTER) if d: return dictToObject(d, self.clz()) else: # TODO: logger return None
def batchUpdate(self, filter={}, update={}): if "isValid" in filter.keys(): filter["isValid"] = True result = self.c.update_many(filter, update) r = dict() r["total"] = result.matched_count r["offset"] = 0 sets = [] for c in result.raw_result: sets.append(dictToObject(c, self.clz())) r["result"] = sets return r
def create(self, entity): if isinstance(entity, self.clz): entity.id = get_increment_id(self.collectionName) d = objectToDict(entity) d["_id"] = d.get("id") d["isValid"] = True set_doc_create_time(d) set_doc_update_time(d) self.c.save(d) d = self.c.find_one({"id": entity.id}) return dictToObject(d, self.clz()) else: return None