Skip to content

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
  1. Import Optional from typing(Python standard module) to declare fields that could be None.

  2. Import connect and Document from mongodb_odm. connect function will be used to set connection with database. Use Document class as a parent class of our database models.

  3. Create the Player model class, representing the player collection in the database.

  4. Create the name field. The field was a required, so there's no default value, and it's not Optional.

  5. The country_code field will behave as an plain string field as like name

  6. Create the rating nullable int field. In the database, the default value will be null, the python equivalent of None. As this field could be None (and null in the database), we declare it with Optional[int].

  7. 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 the main() function.

  8. 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 function main() in the main block below. As it is a single function, other Python files could import it and call it directly.

  9. We set connection with our database by passing connection string in the function connect that import from mongodb_odm.

  10. And now we are also creating the players in this main() function.

  11. Here we create all Player compact in a function for better understandability.

  12. We created our first object. Create the data in database by calling create() method.

  13. We declare second Player object. We did not save/create data in the database instantly.

  14. We save all data to database by calling create() method of maradona object 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
  1. Import Optional from typing(Python standard module) to declare fields that could be None.

  2. Import connect and Document from mongodb_odm. connect function will be used to set connection with database. Use Document class as a parent class of our database models.

  3. Create the Player model class, representing the player collection in the database.

  4. Create the name field. The field was a required, so there's no default value, and it's not Optional.

  5. The country_code field will behave as an plain string field as like name

  6. Create the rating nullable int field. In the database, the default value will be null, the python equivalent of None. As this field could be None (and null in the database), we declare it with Optional[int].

  7. 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 the main() function.

  8. 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 function main() in the main block below. As it is a single function, other Python files could import it and call it directly.

  9. We set connection with our database by passing connection string in the function connect that import from mongodb_odm.

  10. And now we are also creating the players in this main() function.

  11. Here we create all Player compact in a function for better understandability.

  12. We created our first object. Create the data in database by calling create() method.

  13. We declare second Player object. We did not save/create data in the database instantly.

  14. We save all data to database by calling create() method of maradona object 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
  1. Import Optional from typing(Python standard module) to declare fields that could be None.

  2. Import connect and Document from mongodb_odm. connect function will be used to set connection with database. Use Document class as a parent class of our database models.

  3. Create the Player model class, representing the player collection in the database.

  4. Create the name field. The field was a required, so there's no default value, and it's not Optional.

  5. The country_code field will behave as an plain string field as like name

  6. Create the rating nullable int field. In the database, the default value will be null, the python equivalent of None. As this field could be None (and null in the database), we declare it with Optional[int].

  7. 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 the main() function.

  8. 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 function main() in the main block below. As it is a single function, other Python files could import it and call it directly.

  9. We set connection with our database by passing connection string in the function connect that import from mongodb_odm.

  10. And now we are also creating the players in this main() function.

  11. Here we create all Player compact in a function for better understandability.

  12. We created our first object. Create the data in database by calling create() method.

  13. We declare second Player object. We did not save/create data in the database instantly.

  14. We save all data to database by calling create() method of maradona object 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)
  1. Import Optional from typing(Python standard module) to declare fields that could be None.

  2. Import connect and Document from mongodb_odm. connect function will be used to set connection with database. Use Document class as a parent class of our database models.

  3. Create the Player model class, representing the player collection in the database.

  4. Create the name field. The field was a required, so there's no default value, and it's not Optional.

  5. The country_code field will behave as an plain string field as like name

  6. Create the rating nullable int field. In the database, the default value will be null, the python equivalent of None. As this field could be None (and null in the database), we declare it with Optional[int].

  7. 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 the main() function.

  8. 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 function main() in the main block below. As it is a single function, other Python files could import it and call it directly.

  9. We set connection with our database by passing connection string in the function connect that import from mongodb_odm.

  10. And now we are also creating the players in this main() function.

  11. Here we create all Player compact in a function for better understandability.

  12. We created our first object. Create the data in database by calling create() method.

  13. We declare second Player object. We did not save/create data in the database instantly.

  14. We save all data to database by calling create() method of maradona object that are previously defined.