DEV Community

Cover image for MongoDb with Python
petercour
petercour

Posted on

1

MongoDb with Python

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"

Installation

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

First install MongoDb if it's not installed. You can find a nice install guide for ubuntu here.

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 JSON like structure. The two other common database operations are update and delete.

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:

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry πŸ‘€

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more β†’

Top comments (0)

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay