In the previous articles, we installed MongoDB, PyMongo and also established connections between MongoDB and Python.
Check the following articles if you haven’t done already. In this tutorial, we are going to see how to create MongoDB database and insert documents init.

Create MongoDB database:

Before moving further, let’s understand what database, collection and document are in MongoDB.

A MongoDB database is made up of collections, each collection is made up of documents, and the documents consists of data. A document is the smallest unit of data storage in a MongoDB database.

A MongoDB document uses Binary Javascript Object Notation(BSON) style to store data. A collection is like a table in RDBMS which can store numerous documents. A database stores one or more collections of documents.

Now let’s create a database by calling created client mclient and passing the name of the database we want to create.

Run:

from pymongo import MongoClient
mclient = MongoClient('localhost', 27017)
db = mclient['Newdatabase']
print("Database created Successfully")
mclient.close()

Output:

Database created Successfully

Since a database in MongoDB is not created until it receives content, we should first build a document and a collection before testing if the database exists.

The above output doesn’t assure us if the database Newdatabase is created or not. It’s just the print() method doing its job.

Creating Collection:

We can create a collection by using the database object and the name of the collection we want to create.
Run:

from pymongo import MongoClient
mclient = MongoClient('localhost', 27017)
db = mclient['Newdatabase']
print("Database is created !!")
mcol = db["Employers"]
mclient.close()

MongoDB won’t create a collection until it receives content. Now, let’s create a document or insert a record.

Creating document:

Creating a document in MongoDB is like inserting a record in RDBMS. Now let’s create a document.

Using insert_one() method:

To create a document we use insert_one(). We will pass a dictionary as a first parameter with a name and value to be inserted as a record.

Run:

from pymongo import MongoClient
mclient = MongoClient('localhost', 27017) 
db = mclient['Newdatabase']
print("Database is created !!")
mcol = db["Employers"]
mdict = { "f_name": "Rob", "l_name": "Carpenter" }
mid = mcol.insert_one(mdict)
mclient.close()

This will insert a record into the collection. The insert_one() function returns an InsertOneResult object with the inserted id property holding the inserted document’s id.

If we don’t supply an _id field in the input dict, MongoDB will create it automatically and assign each document with a unique id.
Let’s see what unique id is assigned to our mdict.
Run:

from pymongo import MongoClient
mclient = MongoClient('localhost', 27017) 
db = mclient['Newdatabase']
print("Database is created !!")
mcol = db["Employers"]
mdict = { "f_name": "Rob", "l_name": "Carpenter" }
mid = mcol.insert_one(mdict)
print(mid.inserted_id)
mclient.close()

Output:

Database is created !!
6197f7eb588c1566078fbff2

As seen in the output, our code is working perfectly. It created the database and inserted a document into the collection.

Using insert_many():

insert_many() method is used to insert multiple documents. It takes a list containing dictionaries with the data we want to insert as a first parameter.

Run:

from pymongo import MongoClient
mclient = MongoClient('localhost', 27017) 
db = mclient['Newdatabase']
mcol = db["Employers"]

mlist = [
  { "f_name": "Nil", "l_name": "Mil" },
  { "f_name": "Andy", "l_name": "Apple" },
  { "f_name": "AMad", "l_name": "Amhed" },
  ]

mid = mcol.insert_many(mlist)
print(mid.inserted_ids)
mclient.close()

Output:

[ObjectId('619800106f7cca5b81de7ec7'), ObjectId('619800106f7cca5b81de7ec8'), ObjectId('619800106f7cca5b81de7ec9')]

Insert Multiple Documents, with Specific IDs:

It’s inserting multiple records using insert_many() method but specifying IDs by ourselves. Let’s insert IDs as _id and run:
Run:

from pymongo import MongoClient
mclient = MongoClient('localhost', 27017) 
db = mclient['Newdatabase']
mcol = db["Employers"]

mlist = [
  { "_id": 1, "f_name": "Nil", "l_name": "Mil" },
  { "_id": 2, "f_name": "Andy", "l_name": "Apple" },
  { "_id": 3, "f_name": "AMad", "l_name": "Amhed" },
  ]

mid = mcol.insert_many(mlist)
print(mid.inserted_ids)
mclient.close()

Output:

[1, 2, 3]

Note: Two documents or records cannot have the same _id.

References:

Happy Learning 🙂