PYTHON Tutorial

Setting Up MongoDB

MongoDB is a popular NoSQL database management system. It is known for its scalability, flexibility, and ease of use.

Installing MongoDB

For Windows:
  • Go to the MongoDB download page and download the latest version of MongoDB for Windows.
  • Run the downloaded file and follow the on-screen instructions.
  • By default, MongoDB will be installed in the C:\Program Files\MongoDB\Server directory.
For macOS:
  • Go to the MongoDB download page and download the latest version of MongoDB for macOS.
  • Double-click the downloaded file and drag the MongoDB icon to the Applications folder.
  • By default, MongoDB will be installed in the /usr/local/mongodb directory.
For Linux:
  • Add the MongoDB repository to your system:
    sudo apt-get install gnupg
    wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
    echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
    
  • Update your package list:
    sudo apt-get update
    
  • Install MongoDB:
    sudo apt-get install mongodb-org
    

Configuring MongoDB

MongoDB uses a configuration file named mongod.conf to store its settings. This file is located in the following directories:

  • Windows: C:\Program Files\MongoDB\Server\4.4\bin\mongod.conf
  • macOS: /usr/local/mongodb/bin/mongod.conf
  • Linux: /etc/mongod.conf

You can edit the mongod.conf file to change the following settings:

  • Port: The port that MongoDB will listen on. The default port is 27017.
  • Storage: The directory where MongoDB will store its data. The default directory is data.
  • Log file: The file where MongoDB will log its messages. The default file is mongod.log.

Running the MongoDB Server

Once you have installed and configured MongoDB, you can start the server by running the following command in a terminal window:

mongod --config /path/to/mongod.conf

You can now connect to the MongoDB server using a MongoDB client, such as the mongo shell.

Simple Python Example

To connect to MongoDB from Python, you can use the following code:

import pymongo

# Create a client instance
client = pymongo.MongoClient("mongodb://localhost:27017")

# Get a database instance
db = client.mydb

# Get a collection instance
collection = db.mycollection

# Insert a document into the collection
collection.insert_one({"name": "John Doe"})

# Find a document in the collection
result = collection.find_one({"name": "John Doe"})

# Print the document's name
print(result["name"])