MongoDb with Python
Tags: python, database, mongodb
Published: 2019-07-17 12:50:01

---
title: MongoDb with Python
published: true
description: python, database
tags: python, database, mongodb
cover_image: https://proxy.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.solutionanalysts.com%2Fwp-content%2Fuploads%2F2016%2F04%2Fmongodb-developers-guide.jpg%3F6a0c99&f=1
---
You can use MongoDb with Python. So what is MongoDb?

*"MongoDB is a free and open-source cross-platform document-oriented      database program. Classified as a* **NoSQL database** *program, MongoDB 
uses JSON-like documents with schemas. MongoDB is developed by 
MongoDB Inc"*

<img src="https://proxy.duckduckgo.com/iu/?u=https%3A%2F%2Ftse4.mm.bing.net%2Fth%3Fid%3DOIP.8TWOAcQaXSC9aXM_rK_hHQHaFw%26pid%3DApi&f=1">

### Installation 

Let's take a look. The first step is installation.

First install MongoDb if it's not installed. You can find a nice <a href="https://www.digitalocean.com/community/tutorials/how-to-install-mongodb-on-ubuntu-16-04">install guide for ubuntu here</a>. 

Once installed verify it's running:

    sudo systemctl status mongod
    ● mongod.service - High-performance, schema-free document-oriented database
       Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
       Active: active (running) since Wed 2019-07-17 14:27:56 CEST; 5s ago
         Docs: https://docs.mongodb.org/manual
     Main PID: 13083 (mongod)
       CGroup: /system.slice/mongod.service
               └─13083 /usr/bin/mongod --quiet --config /etc/mongod.conf

Is the server running? Great.

### CRUD

Create some Python code. A new collection "myFriends" will be created.
Then records will be inserted. After that's done, it will grab every record.

    #!/usr/bin/python3
    import pymongo

    mongo_client=pymongo.MongoClient('localhost',27017)

    db=mongo_client.myDB                                                                                                                                   
    my_collection=db['myFriends']

    print("="*50)

    tom={'name':'Tom','age':38,'sex':'Male','hobbies':['Cooking','Golf','Tennis']}
    alice={'name':'Alice','age':39,'sex':'Female','hobbies':['Programming','TV','Motorcycle']}
    tom_id=my_collection.insert(tom)
    alice_id=my_collection.insert(alice)
    print(tom_id)
    print(alice_id)


    print("="*25)
    cursor=my_collection.find()
    print(cursor.count())
    for item in cursor:
        print(item)

Output:

    2
    {'_id': ObjectId('5d2f15d742a6c25c8dd7e5bd'), 'name': 'Tom', 'age': 38, 'sex': 'Male', 'hobbies': ['Cooking', 'Golf', 'Tennis']}
    {'_id': ObjectId('5d2f15d842a6c25c8dd7e5be'), 'name': 'Alice', 'age': 39, 'sex': 'Female', 'hobbies': ['Programming', 'TV', 'Motorcycle']}

That's for inserting and reading records. Inserting is what a <a href="https://pythonbasics.org/json/">JSON</a> like structure. The two other common database operations are update and delete.

<img src="https://proxy.duckduckgo.com/iu/?u=https%3A%2F%2Fthumbs.gfycat.com%2FIncredibleRaggedAmphiuma-size_restricted.gif&f=1">

To update and delete:

    #!/usr/bin/python3
    import pymongo
    
    mongo_client=pymongo.MongoClient('localhost',27017)
    
    db=mongo_client.myDB
    my_collection=db['myFriends']
    
    
    print("="*25)
    my_collection.update({'name':'Alice'},{'$set':{'hobbies':['Music']}})
    for item in my_collection.find():
        print(item)
        
    
    print("="*25)
    my_collection.remove({'name':'Tom'})
    for item in my_collection.find():
        print(item)

Output:

    =========================
    {'_id': ObjectId('5d2f15d742a6c25c8dd7e5bd'), 'name': 'Tom', 'age': 38, 'sex': 'Male', 'hobbies': ['Cooking', 'Golf', 'Tennis']}
    {'_id': ObjectId('5d2f15d842a6c25c8dd7e5be'), 'name': 'Alice', 'age': 39, 'sex': 'Female', 'hobbies': ['Music']}
    =========================
    {'_id': ObjectId('5d2f15d842a6c25c8dd7e5be'), 'name': 'Alice', 'age':    39, 'sex': 'Female', 'hobbies': ['Music']}


Related links:
* <a href="https://www.mongodb.com/">MongoDb website</a>
* <a href="https://pythonbasics.org/">Learn Python</a>
* <a href="https://pythonbasics.org/exercises/">Python Exercises</a>