Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To establish a connection between Python and MongoDB on Azure VM, you can follow these steps:

  1. Create an Azure virtual machine and install MongoDB on it.
  2. Install the PyMongo package using pip in your Python environment.
  3. Use the PyMongo driver to connect to the MongoDB instance from your Python code.
  4. In the connection string for PyMongo, include the hostname and port of the Azure virtual machine, and the database name and credentials as needed.

Here's an example Python code to connect to MongoDB from Azure VM:

from pymongo import MongoClient

# Connect to the MongoDB instance
client = MongoClient('mongodb://<username>:<password>@<vm_hostname>:<vm_port>/<db_name>')

# Access a database in MongoDB and create a collection
db = client.testdb
collection = db.testcollection

# Insert a document into the collection
doc = {"name": "John Doe", "age": 30}
result = collection.insert_one(doc)

# Print the inserted document ID
print(result.inserted_id)

In the above code, replace <username>, <password>, <vm_hostname>, <vm_port>, and <db_name> with the appropriate values for your environment.