How To Connect MongoDB And Create Database Collection In Python Source Code

Pymongo is a popular mongo database python driver library. We can use it to manage mongo database. In this article, i will show you how to install pymongo library and how to use pymongo to connect to mongo database. It also tell you how to create mongo database and collection in python source code.

1. Install Pymongo Library.

  1. Open a terminal and run command pip install pymongo to download and install pymongo library.
    $ pip install pymongo
    Collecting pymongo
      Downloading pymongo-3.11.0-cp37-cp37m-macosx_10_9_x86_64.whl (378 kB)
         |████████████████████████████████| 378 kB 112 kB/s 
    Installing collected packages: pymongo
    Successfully installed pymongo-3.11.0
  2. Run command pip show pymongo to verify that pymongo library has been installed in your python virtual environment.
    $ pip show pymongo
    Name: pymongo
    Version: 3.11.0
    Summary: Python driver for MongoDB <http://www.mongodb.org>
    Home-page: http://github.com/mongodb/mongo-python-driver
    Author: Mike Dirolf
    Author-email: [email protected]
    License: Apache License, Version 2.0
    Location: /Users/songzhao/opt/anaconda3/envs/env_ipython_example/lib/python3.7/site-packages
    Requires: 
    Required-by:

2. Verify Pymongo Library Installation.

  1. Create a module file in eclipse pydev project. The file name is MongoDBConnect.py. You can read article How To Run Python In Eclipse With PyDev.
    create mongo db connect module use pymongo in eclipse pydev
  2. Import pymongo library in your python source code. If there is a red line under the import pymongo code, this means it can not find the pymongo library in current python interpreter, you can read article How To Change Python Interpreter In Eclipse Pydev Project To Use Different Python Virtual Environment Library. If there is not any code error( a red line under the import pymongo code, it means the pymongo has been installed in this project used interpreter. )
    import pymongo

2. Create Mongo Database And Collection Steps Use Pymongo.

2.1 Connect To Mongo Database Server Steps.

  1. Import pymongo.MongoClient module.
    from pymongo import MongoClient
  2. Create an instance of pymongo.MongoClient .
    client = MongoClient(db_host, db_port)
  3. Now you can use the client object to create mongo database, collecton and insert document.

2.2 Create Mongo Database Steps.

  1. Get mongo database connection object as 2.1 section.
  2. Then run below code to create ( if the database do not exist ) or get ( if the database already exist ) the database.
    db = client[db_name]
  3. If above database do not exist, then it will create a new database in mongo database server. But only when you insert the first document into the database’s collection, then the database will be created. Otherwise, you will not see the database in MongoDB compass.

2.3 Create Mongo Database Collection Steps.

The collection is similar to table in relational database, below is the steps to create ( if not exist ) or get ( if exist ) a collection.

  1. First get the database object where you want to create or get collection as section 2.2.
  2. Then run below code to create or get the collection by collection name.
    db = client[db_name]
    
    collection = db[collection_name]

2.4 Insert One Document Into Mongo Database Collection Steps.

Only after you insert one document into mongo database’s collection, the database and collection will be created if not exist before.

  1. Prepare a python dictionary object ( a jason string ) as the document which will be inserted into the mongo database collection.
    doc_dict = {'user_name':'hello', 'password':'haha', 'email':'[email protected]'}
  2. Then invoke mongo database collection’s insert_one function to insert above dictionray object into the collection.
    collection.insert_one(doc_dict)

2.5 Create Mongo Database And Collection Examples.

In below example, it will demonstrate how to get connection to mongo database server, how to create database, collection and insert document into mongo database collection. The database and collection will be created only after you insert one document into the collection. You can see code comments for detail explaination.

'''
Created on Sep 9, 2020

@author: songzhao
'''

# import pymongo.
import pymongo

# import pymongo.MongoClient, we will use this class to create mongo database server connection object.
from pymongo import MongoClient

# database host and port number are saved in global variable.
db_host = 'localhost'

db_port = 27017

# get mongo database server connection object.
client = MongoClient(db_host, db_port)


''' This function will create a mongo database use the pass in db_name.

    But the database do not created in the mongo database server at once.
    
    Only when you insert a document into the database collection, then the database and the collection will be created in mongo db server.
'''
def create_mongo_db(db_name):
    
    # if database exist then return the database, otherwise it will create the database with name db_name and return the database.
    db = client[db_name]
    
    print('Mongo database ', db_name, ' has been created.')
    
    # list all mongo database name.
    db_name_list = client.list_database_names()
    
    print('Database name list : ', db_name_list)
    
# check whether the database exist or not.    
def is_mongo_db_exist(db_name):
     
     # get all database name list.    
     db_list = client.list_database_names()    

     if db_name in db_list:
         
         print('Mongo database ', db_name, ' exist.')
         
     else:
          
         print('Mongo database ', db_name, ' do not exist.')
         
 
'''
   This function will create a collection.

'''         
def create_collection(db_name, collection_name):
     
     # create or get the database first.    
     db = client[db_name]
     
     # if the collection exist then return it, otherwise it will create the collection with name collection_name.
     collection = db[collection_name]
     
     print('Database : ', db_name, ', Collection : ',collection_name  ,' has been created.')
     
     collection_name_list = db.list_collection_names()
     
     print('Database : ', db_name, ' Collection name  list : ', collection_name_list)
     
     
'''
    Check whether the collection exist or not. 
'''     
def is_collection_exist(db_name, collection_name):
    
     # get the database.
     db = client[db_name]
     
     # get collection list in the database.
     collection_name_ist = db.list_collection_names()
     
     if collection_name in collection_name_ist:
         
         print('Database : ', db_name, ', Collection : ',collection_name  ,' exist.')
         
     else:
         
         print('Database : ', db_name, ', Collection : ',collection_name  ,' do not exist.')
 
 
'''
   Insert one document to the database's collection.
   The document data is saved in a dictionary type variable.
'''         
def insert_one_document(db_name, collection_name, doc_dict):
    # create or get the database by name.
    db = client[db_name]
     
    # create or get the collection in above database by name. 
    collection = db[collection_name]         
     
    # insert the document. 
    collection.insert_one(doc_dict)
             
if __name__ == '__main__':
    

    db_name = 'test_db'
    collection_name = 'test_collection'
    doc_dict = {}

    # create database.
    create_mongo_db(db_name)
    # you can not see the database exist.
    is_mongo_db_exist(db_name)
    
    # create collection.
    create_collection(db_name, collection_name)
    # you can not see the collection exist.
    is_collection_exist(db_name, collection_name)
    
    # insert one document to the database and collection.
    doc_dict = {'user_name':'jerry', 'password':'def'}
    insert_one_document(db_name, collection_name, doc_dict)
    # after insert document, the database and collection exist in mongo database server.
    is_mongo_db_exist(db_name)
    is_collection_exist(db_name, collection_name)
    
    # insert a new document to a new mongo database and collection.
    db_name = 'user_account'
    collection_name = 'account_info'
    doc_dict = {'user_name':'hello', 'password':'haha', 'email':'[email protected]'}
    insert_one_document(db_name, collection_name, doc_dict)
    is_mongo_db_exist(db_name)
    is_collection_exist(db_name, collection_name)

Below is above source code execution result.

Mongo database  test_db  has been created.
Database name list :  ['admin', 'config', 'local']
Mongo database  test_db  do not exist.
Database :  test_db , Collection :  test_collection  has been created.
Database :  test_db  Collection name  list :  []
Database :  test_db , Collection :  test_collection  do not exist.
Mongo database  test_db  exist.
Database :  test_db , Collection :  test_collection  exist.
Mongo database  user_account  exist.
Database :  user_account , Collection :  account_info  exist.

You can see the newly created mongo database and collection in MongoDB compass.

READ :   How To Pass Parameters To View Via Url In Django

create mongo database collection and insert one document into it

Reference

  1. How To Install Mongodb On Mac

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.