async def random_quote(client: AsyncIOMotorClient = Depends(get_odm)): engine = AIOEngine(motor_client=client, database="quotes") collection = engine.get_collection(Quote) # random sample quote = await collection.aggregate([{ '$sample': { 'size': 1 } }]).to_list(length=1) # convert aggregation list to Quote class quote = Quote( quote_text=quote[0]['quote_text'], quote_origin=quote[0]['quote_origin'], ) return quote
async def count_by_status(client: AsyncIOMotorClient = Depends(get_odm)): engine = AIOEngine(motor_client=client, database="backlogs") collection = engine.get_collection(BacklogGame) results = await collection.aggregate([{ '$group': { '_id': '$game_status', 'count': { '$sum': 1 } } }]).to_list(length=None) stats = {result.get('_id'): result.get('count') for result in results} sorted_stats = dict( sorted(stats.items(), key=lambda item: item[1], reverse=True)) return sorted_stats
async def playtime(client: AsyncIOMotorClient = Depends(get_odm)): engine = AIOEngine(motor_client=client, database="backlogs") collection = engine.get_collection(BacklogGame) results = await collection.aggregate([{ '$group': { '_id': None, 'total_hours': { '$sum': '$game_hours' }, 'total_minutes': { '$sum': '$game_minutes' } } }]).to_list(length=None) # move chunks of 60 minutes into the hours count leftover_minutes = results[0].get('total_minutes') % 60 hours_to_move = (results[0].get('total_minutes') - leftover_minutes) / 60 results[0]['total_hours'] = int(results[0]['total_hours'] + hours_to_move) results[0]['total_minutes'] = int(leftover_minutes) return results[0]
from odmantic import AIOEngine, Model class User(Model): name: str engine = AIOEngine() motor_collection = engine.get_collection(User) print(motor_collection) #> AsyncIOMotorCollection( #> Collection( #> Database( #> MongoClient( #> host=["localhost:27017"], #> document_class=dict, #> tz_aware=False, #> connect=False, #> driver=DriverInfo(name="Motor", version="2.2.0", platform="asyncio"), #> ), #> "test", #> ), #> "user", #> ) #> )
length: float width: float rectangles = [ Rectangle(length=0.1, width=1), Rectangle(length=3.5, width=1), Rectangle(length=2.87, width=5.19), Rectangle(length=1, width=10), Rectangle(length=0.1, width=100), ] engine = AIOEngine() await engine.save_all(rectangles) collection = engine.get_collection(Rectangle) pipeline = [] # Add an area field pipeline.append( { "$addFields": { "area": { "$multiply": [++Rectangle.length, ++Rectangle.width] } # Compute the area remotely } } ) # Filter only rectanges with an area lower than 10 pipeline.append({"$match": {"area": {"$lt": 10}}}) # Project to keep only the defined fields (this step is optional) pipeline.append(