Today I Learned About Mongodb
Intro
I started building using NoSQL database and preferred MongoDB. Here are my solutions to some problems I ocurred while I build stuff with it.
Solutions
query without Object ID
If otherwise defined, MongoDB has default primary key on each document after insertion.
![[mongodb-objectid.png]]
This can create issues while querying from an api service as ORM object on non-specific queries. It is possible to exclude it using {'_id': 0}
example query:
result = collection.find_one(
{
'scale': 'global',
'region': 'south america',
'domain': 'nations'
},
{'_id': 0}
)
sorting historical query results
Historical queries are not returned in sorted order by default. To do asc/desc sorting on specific key you can:
db["collection_name"].find({'scale': 'global'}).sort('created_at', -1)
Sort orders are:
- -1 = Ascending
- 1 = Descending
using python reserved keyword as document key
Some variable/key names are reserved on Python, such as “class”. In order to create an ORM model representing documents with “class” key, you should pre/postfix a minor symbol to it: “class_” on the model.
You convert back to its key valueon ORM model using pydantic schemas.
class User(BaseModel):
id: int
Class_: bool
class Config:
fields = {
'class_': 'class'
}