def create_cars(count=200):
    current_car_count = Car.objects().count()
    if current_car_count >= count:
        print("There are currently {:,} cars. Skipping create.")
        return []

    count = count - current_car_count

    hp_factor = 660
    mpg_factor = 21
    liters_factor = 4

    cars = []
    print("Building cars...")
    for _ in range(0, count):
        model = random.choice(models)
        make = 'Ferrari'
        year = random.randint(1985, datetime.now().year)
        mileage = random.randint(0, 150000)

        mpg = int((mpg_factor + mpg_factor * random.random() / 4) * 10) / 10.0
        horsepower = int(hp_factor + hp_factor * random.random() / 2)
        liters = int((liters_factor + liters_factor * random.random() / 2) * 100) / 100.0

        engine = Engine(horsepower=horsepower, liters=liters, mpg=mpg)
        car = Car(model=model, make=make, year=year, engine=engine, mileage=mileage)
        cars.append(car)

    print("Saving cars...")
    Car.objects().insert(cars)

    return list(Car.objects())
def create_cars(count=200):
    current_car_count = Car.objects().count()
    if current_car_count >= count:
        print("There are currently {:,} cars. Skipping create.")
        return []

    count = count - current_car_count

    hp_factor = 660
    mpg_factor = 21
    liters_factor = 4

    cars = []
    print("Building cars...")
    for _ in range(0, count):
        model = random.choice(models)
        make = 'Ferrari'
        year = random.randint(1985, datetime.now().year)
        mileage = random.randint(0, 150000)

        mpg = int((mpg_factor + mpg_factor * random.random() / 4) * 10) / 10.0
        horsepower = int(hp_factor + hp_factor * random.random() / 2)
        liters = int((liters_factor + liters_factor * random.random() / 2) * 100) / 100.0

        engine = Engine(horsepower=horsepower, liters=liters, mpg=mpg)
        car = Car(model=model, make=make, year=year, engine=engine, mileage=mileage)
        cars.append(car)

    print("Saving cars...")
    Car.objects().insert(cars)

    return list(Car.objects())
def percent_cars_with_bad_service():
    t0 = datetime.datetime.now()
    bad = Car.objects().filter(service_history__customer_rating__lte=1).count()
    dt = datetime.datetime.now() - t0
    print("bad computed in {} ms, bad: {:,}".format(dt.total_seconds() * 1000, bad))

    all_cars = Car.objects().count()

    percent = 100 * bad / max(all_cars, 1)
    return percent
def percent_cars_with_bad_service():
    t0 = datetime.datetime.now()
    bad = Car.objects().filter(service_history__customers_rating__lte=1).count()
    dt = datetime.datetime.now() - t0
    print('bad computed in {} ms, bad: {:,}'.format(dt.total_seconds() * 1000, bad))

    all_cars = Car.objects().count()

    percent = 100 * bad / max(all_cars, 1)
    return percent
def service_car():
    # vin = input("What is the VIN of the car to service? ")
    # car = Car.objects(vi_number=vin).first()
    # if not car:
    #     print("Car with VIN {} not found!".format(vin))
    #     return
    #
    # service = ServiceHistory()
    # service.price = float(input("What is the price? "))
    # service.description = input("What type of service is this? ")
    # service.customer_rating = int(input("How happy is our customer? [1-5] "))
    #
    # car.service_history.append(service)
    # car.save()

    vin = input("What is the VIN of the car to service? ")
    service = ServiceHistory()
    service.price = float(input("What is the price? "))
    service.description = input("What type of service is this? ")
    service.customer_rating = int(input("How happy is our customer? [1-5] "))

    updated = Car.objects(vi_number=vin).update_one(push__service_history=service)
    if updated == 0:
        print("Car with VIN {} not found!".format(vin))
        return
Exemple #6
0
def service_car():
    # vin = input("What is the VIN of the car to service? ")
    # car = Car.objects(vi_number=vin).first()
    # if not car:
    #     print("Car with VIN {} not found!".format(vin))
    #     return

    # service = ServiceHistory()
    # service.price = float(input("What is the price? "))
    # service.description = input("What type of service is this? ")
    # service.customer_rating = int(input("How happy is our customer? [1-5] "))

    # car.service_history.append(service)
    # car.save()

    vin = input("What is the VIN of the car to service? ")
    service = ServiceHistory()
    service.price = float(input("What is the price? "))
    service.description = input("What type of service is this? ")
    service.customer_rating = int(input("How happy is our customer? [1-5] "))

    updated = Car.objects(vi_number=vin).update_one(
        push__service_history=service)
    if updated == 0:
        print("Car with VIN {} not found!".format(vin))
        return
def service_car():
    # vin = input('What is the vin of the car to service? ')
    # car = Car.objects().filter(vi_number=vin).first()
    # if not car:
    #     print('Car with VIN {} not found'.format(vin))
    #     return

    # print('We will service '+ car.model)
    # service = ServiceHistory()
    # service.price = float(input('What is the price? '))
    # service.description = input('What type of service is this? ')
    # service.customer_rating = int(input('How happy our costumer? [1-5]'))

    # car.service_history.append(service)
    # car.save()

    vin = input('What is the vin of the car to service? ')
    service = ServiceHistory()
    service.price = float(input('What is the price? '))
    service.description = input('What type of service is this? ')
    service.customer_rating = int(input('How happy our costumer? [1-5] '))

    updated = Car.objects(vi_number=vin).update_one(
        push__service_history=service)
    if updated == 0:
        print("Car with VIN {} not found!\n".format(vin))
        return
Exemple #8
0
def add_service_record(car_id, description, price, customer_rating):
    record = ServiceRecord(description=description,
                           price=price,
                           customer_rating=customer_rating)

    res = Car.objects(id=car_id).update_one(push__service_history=record)
    if res != 1:
        raise Exception("No car with id {}".format(car_id))
Exemple #9
0
def list_cars():
    cars = Car.objects().order_by("-year")
    for car in cars:
        print("{} -- {} with vin {} (year {})".format(car.make, car.model,
                                                      car.vi_number, car.year))
        print("{} of service records".format(len(car.service_history)))
        for s in car.service_history:
            print("  * ${:,.0f} {}".format(s.price, s.description))
    print()
def list_cars():
    cars = Car.objects().order_by("-year")
    for car in cars:
        print("{} -- {} with vin {} (year {})".format(
            car.make, car.model, car.vi_number, car.year))
        print("{} of service records".format(len(car.service_history)))
        for s in car.service_history:
            print("  * ${:,.0f} {}".format(s.price, s.description))
    print()
def list_cars():
    cars = Car.objects().order_by('-year')
    for car in cars:
        print(
            f'{car.make} -- {car.model} with vin {car.vi_number} (year {car.year})'
        )
        print(f'{len(car.service_history)} of service records\n')
        for s in car.service_history:
            print('   * ${:,.0f} {}'.format(s.price, s.description))
    print()
Exemple #12
0
def list_cars():

    cars = Car.objects().order_by("-year")
    for car in cars:
        print(
            f"{car.make} -- {car.model} with vin {car.vi_number} year {car.year}"
        )
        print(f"{len(car.service_history)}")
        for s in car.service_history:
            print(f"      *   ${s.price} {s.description}")
        print()
    print()
def show_poorly_serviced_cars():
    level = int(input("What max level of satisfaction are we looking for? [1-5] "))
    # { "service_history.customer_rating": {$lte: level} }
    cars = Car.objects(service_history__customer_rating__lte=level)
    for car in cars:
        print("{} -- {} with vin {} (year {})".format(
            car.make, car.model, car.vi_number, car.year))
        print("{} of service records".format(len(car.service_history)))
        for s in car.service_history:
            print("  * Satisfaction: {} ${:,.0f} {}".format(
                s.customer_rating, s.price, s.description))
    print()
Exemple #14
0
def show_poorly_serviced_cars():
    level = int(
        input("What max level of satisfaction are we looking for? [1-5] "))
    # { "service_history.customer_rating": {$lte: level} }
    cars = Car.objects(service_history__customer_rating__lte=level)
    for car in cars:
        print("{} -- {} with vin {} (year {})".format(car.make, car.model,
                                                      car.vi_number, car.year))
        print("{} of service records".format(len(car.service_history)))
        for s in car.service_history:
            print("  * Satisfaction: {} ${:,.0f} {}".format(
                s.customer_rating, s.price, s.description))
    print()
def service_car():
    vin = input("What is the VIN of the car to service? ")
    service = ServiceHistory()
    service.price = float(input("What is the price of service? "))
    service.description = input("What type of service is this? ")
    service.customer_rating = int(input("How happy is our customer? [1-5] "))

    updated = Car.objects().filter(vi_number=vin).update_one(
        push__service_history=service)  # it does update the doc, if
    # it finds it, will return 1, if not returns 0.
    if updated == 0:
        print("Car with VIN {} not found!".format(vin))
        return
def show_poor_serviced_cars():
    level = int(
        input('What max level of satisfaction are we looking for? [1-5] '))

    #  {'service_history.customres_reting': {$lte: level} }
    cars = Car.objects(service_history__customer_rating__lte=level)
    for car in cars:
        print()
        print(
            f'{car.make} -- {car.model} with vin {car.vi_number} (year {car.year})'
        )
        print(f'{len(car.service_history)} of service records\n')
        for s in car.service_history:
            print('   * Stisfaction: {} ${:,.0f} {}\n'.format(
                s.customer_rating, s.price, s.description))
def main():
    mongo_setup.init()

    print("Computing stats, this WILL take awhile...", flush=True)

    cars = list(Car.objects())
    print("There are {:,} cars.".format(len(cars)))

    owners = list(Owner.objects())
    print("There are {:,} owners.".format(len(owners)))
    owned_cars = sum((len(o.car_ids) for o in owners))
    print("Each owner owns an average of {:.2f} cars.".format(owned_cars / len(owners)))

    service_histories = sum((len(c.service_history) for c in cars))
    print("There are {:,} service histories.".format(service_histories))
    print("Each car has an average of {:.2f} service records.".format(service_histories / len(cars)))
def main():
    mongo_setup.init()

    print("Computing stats, this WILL take awhile...", flush=True)

    cars = list(Car.objects())
    print("There are {:,} cars.".format(len(cars)))

    owners = list(Owner.objects())
    print("There are {:,} owners.".format(len(owners)))
    owned_cars = sum((len(o.car_ids) for o in owners))
    print("Each owner owns an average of {:.2f} cars.".format(owned_cars /
                                                              len(owners)))

    service_histories = sum((len(c.service_history) for c in cars))
    print("There are {:,} service histories.".format(service_histories))
    print("Each car has an average of {:.2f} service records.".format(
        service_histories / len(cars)))
def find_car_by_id(car_id: bson.ObjectId) -> Car:
    car = Car.objects(id=car_id).first()
    Car.objects().filter(id=car_id).first()
    return car
def find_car_with_bad_service(limit=10) -> typing.List[Car]:
    cars = Car.objects(sevice_history__customer_rating__lte=1)[:limit]
    return list(cars)
def find_cars_by_make(make):
    car = Car.objects(make=make).first()
    return car
def find_cars_by_make(make) -> Car:
    car = Car.objects(make=make).first()
    return car
def find_cars_with_bad_service(limit=10) -> typing.List[Car]:
    cars = Car.objects(service_history__customer_rating__lt=4)[:limit]
    return list(cars)
Exemple #24
0
def update_doc_versions():
    for car in Car.objects():
        car._mark_as_changed('vi_number')
        car.save()
def find_car_by_id(car_id: bson.ObjectId) -> Car:
    car = Car.objects(id=car_id).first()
    Car.objects().filter(id=car_id).first()
    return car
def add_service_record(car_id, description, price, customer_rating):
    record = ServiceRecord(description=description, price=price, customer_rating=customer_rating)

    res = Car.objects(id=car_id).update_one(push__service_history=record)
    if res != 1:
        raise Exception("No car with id {}".format(car_id))
    return list(cars)


timed(
    'How many cars are owned by the 10,000th owner?',
    lambda: find_cars_by_owner(owner.id)
)


def find_owners_by_car(car_id):
    print(car_id)
    owners = Owner.objects(car_ids=car_id)
    return list(owners)


car = Car.objects()[10000:10001][0]
timed(
    'How many owners own the 10,000th car?',
    lambda: find_owners_by_car(car.id)
)

owner50k = Owner.objects()[50000:50001][0]
timed(
    'Find owner 50,000 by name?',
    lambda: Owner.objects(name=owner50k.name).first()
)

timed(
    'Cars with expensive service?',
    lambda: Car.objects(service_history__price__gt=16800).count()
)
def find_cars_by_owner(owner_id):
    the_owner = Owner.objects(id=owner_id).first()
    cars = Car.objects().filter(id__in=the_owner.car_ids)
    return list(cars)
    t0 = datetime.now()

    func()

    dt = datetime.now() - t0
    print("{} Time: {:,.3f} ms".format(msg,
                                       dt.total_seconds() * 1000.0),
          flush=True)


mongo_setup.init()

print("Time to ask some questions")

timed('How many owners?', lambda: Owner.objects().filter().count())
timed('How many cars?', lambda: Car.objects().filter().count())

timed('Find the 10,000th owner?',
      lambda: Owner.objects().order_by('name')[10000:10001][0])

owner = Owner.objects().order_by('name')[10000:10001][0]


def find_cars_by_owner(owner_id):
    the_owner = Owner.objects(id=owner_id).first()
    cars = Car.objects().filter(id__in=the_owner.car_ids)
    return list(cars)


timed('How many cars are owned by the 10,000th owner?',
      lambda: find_cars_by_owner(owner.id))