Create¶
Here's a reminder of how the collection would look like, this is the data we want to add:
{
"_id": ObjectId('id'),
"name": "Pelé",
"country_code": "BRA",
"rating": null
}
{
"_id": ObjectId('id'),
"name": "Diego Maradona",
"country_code": "ARG",
"rating": 97
}
{
"_id": ObjectId('id'),
"name": "Zinedine Zidane",
"country_code": "FRA",
"rating": 96
}
Define Model¶
We will continue from where we left off in the Initiate Database and Define Model Chapter.
import os
from typing import Optional # (1)
from mongodb_odm import Document, connect # (2)
class Player(Document): # (3)
name: str # (4)
country_code: str # (5)
rating: Optional[int] = None # (6)
# Code omitted below
-
Import
Optionalfromtyping(Python standard module) to declare fields that could beNone. -
Import
connectandDocumentfrommongodb_odm.connectfunction will be used to set connection with database. UseDocumentclass as a parent class of our database models. -
Create the
Playermodel class, representing theplayercollection in the database. -
Create the
namefield. The field was a required, so there's no default value, and it's not Optional. -
The
country_codefield will behave as an plainstringfield as likename -
Create the
ratingnullable int field. In the database, the default value will benull, the python equivalent ofNone. As this field could beNone(andnullin the database), we declare it withOptional[int]. -
There's a single
main()function now that contains all the code that should be executed when running the program from the console. So this is all we need to have in the main block. Just call themain()function. -
We have a
main()function with all the code that should be executed when the program is called as a script from the console. That way we can add more code later to this function.We then put this functionmain()in the main block below. As it is a single function, other Python files could import it and call it directly. -
We set connection with our database by passing connection string in the function
connectthat import frommongodb_odm. -
And now we are also creating the players in this
main()function. -
Here we create all
Playercompact in a function for better understandability. -
We created our first object. Create the data in database by calling
create()method. -
We declare second
Playerobject. We did not save/create data in the database instantly. -
We save all data to database by calling
create()method ofmaradonaobject that are previously defined.
Create data with MongoDB console¶
Let's create the player collection in test_db and insert one player record using the MongoDB console.
use test_db
db.player.insertOne({
"name": "Pelé",
"country_code": "BRA",
"rating": null,
})
Explore MongoDB database¶
Let's check the MongoDB database and find the player collection in the test_db database.
The collection should have one item on the list.
{
"_id": ObjectId('id'),
"name": "Pelé",
"country_code": "BRA",
"rating": null
}
Set database connection¶
Set the database connection once for a project. It's recommended to set up a connection while the project is initializing.
# Code omitted above
def main(): # (8)
connect(os.environ.get("MONGO_URL", "mongodb://localhost:27017/testdb")) # (9)
create_documents() # (10)
# Code omitted below
-
Import
Optionalfromtyping(Python standard module) to declare fields that could beNone. -
Import
connectandDocumentfrommongodb_odm.connectfunction will be used to set connection with database. UseDocumentclass as a parent class of our database models. -
Create the
Playermodel class, representing theplayercollection in the database. -
Create the
namefield. The field was a required, so there's no default value, and it's not Optional. -
The
country_codefield will behave as an plainstringfield as likename -
Create the
ratingnullable int field. In the database, the default value will benull, the python equivalent ofNone. As this field could beNone(andnullin the database), we declare it withOptional[int]. -
There's a single
main()function now that contains all the code that should be executed when running the program from the console. So this is all we need to have in the main block. Just call themain()function. -
We have a
main()function with all the code that should be executed when the program is called as a script from the console. That way we can add more code later to this function.We then put this functionmain()in the main block below. As it is a single function, other Python files could import it and call it directly. -
We set connection with our database by passing connection string in the function
connectthat import frommongodb_odm. -
And now we are also creating the players in this
main()function. -
Here we create all
Playercompact in a function for better understandability. -
We created our first object. Create the data in database by calling
create()method. -
We declare second
Playerobject. We did not save/create data in the database instantly. -
We save all data to database by calling
create()method ofmaradonaobject that are previously defined.
Create data with MongoDB-ODM¶
Create two players using MongoDB-ODM.
We use the create_documents function to create two players.
First, we create players at declaration time.
Second, we assign a player object to maradona. Then we create/insert the data into the database by calling the create method.
# Code omitted above
def create_documents(): # (11)
Player(name="Pelé", country_code="BRA").create() # (12)
maradona = Player(
name="Diego Maradona", country_code="ARG", rating=97
).create() # (13)
maradona = maradona.create() # (14)
Player(name="Zinedine Zidane", country_code="FRA", rating=96).create()
# Code omitted below
-
Import
Optionalfromtyping(Python standard module) to declare fields that could beNone. -
Import
connectandDocumentfrommongodb_odm.connectfunction will be used to set connection with database. UseDocumentclass as a parent class of our database models. -
Create the
Playermodel class, representing theplayercollection in the database. -
Create the
namefield. The field was a required, so there's no default value, and it's not Optional. -
The
country_codefield will behave as an plainstringfield as likename -
Create the
ratingnullable int field. In the database, the default value will benull, the python equivalent ofNone. As this field could beNone(andnullin the database), we declare it withOptional[int]. -
There's a single
main()function now that contains all the code that should be executed when running the program from the console. So this is all we need to have in the main block. Just call themain()function. -
We have a
main()function with all the code that should be executed when the program is called as a script from the console. That way we can add more code later to this function.We then put this functionmain()in the main block below. As it is a single function, other Python files could import it and call it directly. -
We set connection with our database by passing connection string in the function
connectthat import frommongodb_odm. -
And now we are also creating the players in this
main()function. -
Here we create all
Playercompact in a function for better understandability. -
We created our first object. Create the data in database by calling
create()method. -
We declare second
Playerobject. We did not save/create data in the database instantly. -
We save all data to database by calling
create()method ofmaradonaobject that are previously defined.
Sometimes we need to assign an object and then change some data and insert the data at the end. In that case, use the second approach. First, assign the object, do all necessary changes, and save the document later.
Impact in Database¶
After running the file, we should find the two player documents in the player collection of the test_db database.
Full file code¶
import os
from typing import Optional # (1)
from mongodb_odm import Document, connect # (2)
class Player(Document): # (3)
name: str # (4)
country_code: str # (5)
rating: Optional[int] = None # (6)
def create_documents(): # (11)
Player(name="Pelé", country_code="BRA").create() # (12)
maradona = Player(
name="Diego Maradona", country_code="ARG", rating=97
).create() # (13)
maradona = maradona.create() # (14)
Player(name="Zinedine Zidane", country_code="FRA", rating=96).create()
def main(): # (8)
connect(os.environ.get("MONGO_URL", "mongodb://localhost:27017/testdb")) # (9)
create_documents() # (10)
if __name__ == "__main__":
main() # (7)
-
Import
Optionalfromtyping(Python standard module) to declare fields that could beNone. -
Import
connectandDocumentfrommongodb_odm.connectfunction will be used to set connection with database. UseDocumentclass as a parent class of our database models. -
Create the
Playermodel class, representing theplayercollection in the database. -
Create the
namefield. The field was a required, so there's no default value, and it's not Optional. -
The
country_codefield will behave as an plainstringfield as likename -
Create the
ratingnullable int field. In the database, the default value will benull, the python equivalent ofNone. As this field could beNone(andnullin the database), we declare it withOptional[int]. -
There's a single
main()function now that contains all the code that should be executed when running the program from the console. So this is all we need to have in the main block. Just call themain()function. -
We have a
main()function with all the code that should be executed when the program is called as a script from the console. That way we can add more code later to this function.We then put this functionmain()in the main block below. As it is a single function, other Python files could import it and call it directly. -
We set connection with our database by passing connection string in the function
connectthat import frommongodb_odm. -
And now we are also creating the players in this
main()function. -
Here we create all
Playercompact in a function for better understandability. -
We created our first object. Create the data in database by calling
create()method. -
We declare second
Playerobject. We did not save/create data in the database instantly. -
We save all data to database by calling
create()method ofmaradonaobject that are previously defined.