How to create collections and insert data to collection in MongoDB in Python

Hello programmers, here we are going to learn how to create collections in MongoDB in Python and adding documents to those collections.

Before jumping directly to the Python program, I think we need to know a few things:

  1. Install MongoDB in Python
  2. How to Connect MongoDB with Python
  3. How to create a database in MongoDB

Create collections in MongoDB with Python

Both of them have been covered in the previous tutorials. I would recommend you start with installation on MongoDB and follow step by step process.

MongoDB is a document database. Since it is a document database it does not have tables and rows. It consists of collections that are a group of MongoDB documents.

Creating a collection in MongoDB.

courses = db.courses
print(courses)

Output

Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'CodeSpeedy'), 'courses')

This is the output you should on the successful creation of the collection. Here Codespeedy is the name of the database and courses is the collection in the CodeSpeedy database.

Inserting documents into the collection in MongoDB using Python

For inserting new documents into the collection we make use dictionaries.

For inserting the document use the following code.

course = {
    'author': 'Shailesh Bhimanpelli',
    'age': 21,
    'course': 'MongoDB using Python',
    'rating': 1
}

result = courses.insert_one(course)
print(result)

Output:

<pymongo.results.InsertOneResult object at 0x02FBB558>

Note: It is important to start the MongoDB before executing the code.

Here we have used insert_one command because we are inserting only one document into the collection. The course reference is the dictionary having key-value pairs. We are storing the data of the document in the dictionary. Then we run the command courses.insert_one(course) which inserts the data into the collection.

MongoDB add assigns unique _id to each document. In the above code, we did not any _id so MongoDB will auto assign _id for the document.

print(result.inserted_id)

Output

5dee3fa9cc72840e502eab92

This is the _id for the document we have inserted.

Inserting multiple documents

We can insert multiple documents using insert_many command.

courseMany = [
    {'author': 'Saruque Ahamed Mollick',
    'age': 25,
    'course': 'Python, Java, C++',
    'rating': 5},
    {'author': 'Ben Thomas',
    'age': 23,
    'course': 'HTML, CSS',
    'rating': 3},
    {'author': 'Varun Thakur',
    'age': 25,
    'course': 'JavaScript',
    'rating': 5},
]

resultMany = courses.insert_many(courseMany)
print(resultMany)

Output

<pymongo.results.InsertManyResult object at 0x031AA8F0>

Here we are inserting 3 documents into the collection.

The complete code is given below.

from pymongo import MongoClient

mongo = MongoClient('mongodb://localhost:27017')

# CodeSpeedy is the name of the database
db = mongo.CodeSpeedy

# database for courses offered by CodeSpeedy i.e. courses is the name of the collection
courses = db.courses

print(courses)

# inserting single data
course = {
    'author': 'Shailesh Bhimanpelli',
    'age': 21,
    'course': 'MongoDB using Python',
    'rating': 1
}

result = courses.insert_one(course)


# inserting mulitple data
courseMany = [
    {'author': 'Saruque Ahamed Mollick',
    'age': 25,
    'course': 'Python, Java, C++',
    'rating': 5},
    {'author': 'Ben Thomas',
    'age': 23,
    'course': 'HTML, CSS',
    'rating': 3},
    {'author': 'Varun Thakur',
    'age': 25,
    'course': 'JavaScript',
    'rating': 5},
]

resultMany = courses.insert_many(courseMany)
print(resultMany)

 

Leave a Reply

Your email address will not be published. Required fields are marked *