DEV Community

Cover image for Learn MongoDB + Python basics in 5 minutes !
Siddhesh Shankar
Siddhesh Shankar

Posted on

Learn MongoDB + Python basics in 5 minutes !

What is MongoDB?

MongoDB is a NoSQL database – a NoSQL database is one where you don’t query the database with SQL. Other than that NoSQL really means nothing to define a database. So let’s have another go at defining MongoDB. MongoDB is a JSON document datastore. It allows you to store and query JSON style documents with a few smarts on top. This means that you can store objects with nested data all in one collection (collections are like tables for MongoDB).

What is MongoDB Compass?

MongoDB Compass is the GUI for MongoDB. Compass allows you to analyze and understand the contents of your data without formal knowledge of MongoDB query syntax. Click here to download and watch this video to install compass.

Let's Code

  • Install pymongo. Just open the command prompt and type:
pip install pymongo
Enter fullscreen mode Exit fullscreen mode
  • Open Jupyter Notebook. Let's create a database first.
DEFAULT_CONNECTION_URL = "mongodb://localhost:27017/"
database_name = "Indian_States_DB"

# Establish a connection with mongodb
client = pymongo.MongoClient(DEFAULT_CONNECTION_URL)

## Creating a Database
database = client[database_name]
Enter fullscreen mode Exit fullscreen mode
  • Create a collection. Collection in NoSQL can also be called a table. We have created a empty table below.
# Creating a collection
COLLECTION_NAME = 'Gross_Domestic_Product'
# Adding the collection to our database
collection = database[COLLECTION_NAME]
Enter fullscreen mode Exit fullscreen mode
  • Let's check if our database exists or not.
client.list_database_names()

> ['admin', 'config', 'crawlerDB', 'demoDB', 'local']
Enter fullscreen mode Exit fullscreen mode

The database name does not appear in the above list because there is not data inside Gross_Domestic_Product.

Inserting Records

# Inserting one record
record = {
        "Rank": "1",
        "State": "Maharastra",
        "Nominal GDP ($ Billion)": "400",
        "Data Year": "2019-2020",
        "Comparable Country": "Philippines"
        }
collection.insert_one(record)
Enter fullscreen mode Exit fullscreen mode
# Inserting multiple records
records = [{
        "Rank": "2",
        "State": "Tamil Nadu",
        "Nominal GDP ($ Billion)": "260",
        "Data Year": "2019-2020",
        "Comparable Country": "Vietnam"
        },
        {
        "Rank": "3",
        "State": "Uttar Pradesh",
        "Nominal GDP ($ Billion)": "250",
        "Data Year": "2019-2020",
        "Comparable Country": "Romania"
        },
        {
        "Rank": "4",
        "State": "Karnataka",
        "Nominal GDP ($ Billion)": "240",
        "Data Year": "2019-2020",
        "Comparable Country": "Portugal"
        }]
collection.insert_many(records)
Enter fullscreen mode Exit fullscreen mode
  • Again check if the database exists or not.
client.list_database_names()

> ['Indian_States_DB', 'admin', 'config', 'crawlerDB', 'demoDB', 'local']
Enter fullscreen mode Exit fullscreen mode

Find Records

  • The find() method returns all occurrences in the selection. Select rank and states from the collection.
for i in collection.find({},{"_id":0, "Rank":1, "State":1}):
    print(i)

{'Rank': '1', 'State': 'Maharastra'}
{'Rank': '2', 'State': 'Tamil Nadu'}
{'Rank': '3', 'State': 'Uttar Pradesh'}
{'Rank': '4', 'State': 'Karnataka'}
Enter fullscreen mode Exit fullscreen mode

You are not allowed to specify both 0 and 1 values in the same object (except if one of the fields is the _id field). If you specify a field with the value 0, all other fields get the value 1, and vice versa. For selecting all the records, simply execute find().

Sort

  • Use the sort() method to sort the result in ascending or descending order. Use the value -1 as the second parameter to sort descending.
for i in collection.find({},{"_id":0,"State":1, "Nominal GDP ($ Billion)":1}).sort("State", -1):
    print(i)

{'State': 'Uttar Pradesh', 'Nominal GDP ($ Billion)': '250'}
{'State': 'Tamil Nadu', 'Nominal GDP ($ Billion)': '260'}
{'State': 'Maharastra', 'Nominal GDP ($ Billion)': '400'}
{'State': 'Karnataka', 'Nominal GDP ($ Billion)': '240'}
Enter fullscreen mode Exit fullscreen mode

Limit the Result

  • To limit the result in MongoDB, we use the limit() method.
for i in collection.find({},{"_id":0, "Rank":1, "State":1, "Comparable Country":1}).limit(2):
    print(i)

{'Rank': '1', 'State': 'Maharastra', 'Comparable Country': 'Philippines'}
{'Rank': '2', 'State': 'Tamil Nadu', 'Comparable Country': 'Vietnam'}
Enter fullscreen mode Exit fullscreen mode

Delete Records

To delete one document, we use the delete_one() method. To delete more than one document, use the delete_many() method.

collection.delete_one({"State": "Maharastra"})

for i in collection.find():
    print(i)

{'_id': ObjectId('5f8ae0347d1ce4be5cea8007'), 'Rank': '2', 'State': 'Tamil Nadu', 'Nominal GDP ($ Billion)': '260', 'Data Year': '2019-2020', 'Comparable Country': 'Vietnam'}
{'_id': ObjectId('5f8ae0347d1ce4be5cea8008'), 'Rank': '3', 'State': 'Uttar Pradesh', 'Nominal GDP ($ Billion)': '250', 'Data Year': '2019-2020', 'Comparable Country': 'Romania'}
{'_id': ObjectId('5f8ae0347d1ce4be5cea8009'), 'Rank': '4', 'State': 'Karnataka', 'Nominal GDP ($ Billion)': '240', 'Data Year': '2019-2020', 'Comparable Country': 'Portugal'}
Enter fullscreen mode Exit fullscreen mode

This was all about basics of MongoDB. Hope you like my explanation. Furthermore, if you have any query, feel free to ask in a comment section.

Top comments (0)