How do I use Visual Studio Code to connect to a newly created MongoDB collection?

Viewed 497

I saw this question was asked once before but the answer did not help my situation.

I am a beginner software development student trying to connect Visual Studio Code to a newly created collection in MongoDB and display the collection, through a python file. I'm sorry if that explanation doesn't use established terminology, I'm not entirely sure what I'm doing yet. I am using the code my professor provided and yet I get a whole host of syntax errors and a message that says there is no module named MongoClient. I am not allowed to use anything but VS Code so trying a different environment isn't an option. Here is my code:


Import MongoClient

from pymongo import MongoClient

url = “mongodb+srv://admin:admin@cluster0.zcfrz.mongodb.net/pytech?retryWrites=true”

client = MongoClient(url)

db = client.pytech

print(db.list_collection_names)

Any guidance would be truly appreciated.

3 Answers

You Got this error saying there is no MongoClient simply because of the first line. You can't import MongoClient directly you need to import it from pymongo.

you can read more about how to use pymongo on the official docs.

So the correct way based on the code you provided is (just remove the first line):

from pymongo import MongoClient

url = "mongodb+srv://admin:admin@cluster0.zcfrz.mongodb.net/pytech?retryWrites=true"

client = MongoClient(url)

db = client.pytech

print(db.list_collection_names)

Also you need to make sure you have pymongo installed. to do that read this on the python pypi. I'm assuming you have pytyhon3 and pip3 installed . it's simple and straight forward just use pip to install it :

pip3 install pymongo

Alternatively :

python3 -m pip install pymongo

Also : i noticed you are mongodb+srv protocol so you need to install dnspython as well :

pip install dnspython

Looks like I was missing a "()" in my last line of code. I had print(db.list_collection_names), but what was needed was print(db.list_collection_names()). Since list_collection_names is a function I needed another set of parenthesis inside the print call.

Check if there's surfix like venv or conda in your selected python interpreter located in lower left corner of VS Code. If not, you're not using any virtual environment but global one.

pythonpath is in Settings.json and could be generated automatically by selecting python interpreter. Run pip show pymongo in integrated Terminal to check if the module is located in current selected python environment. If it is, then you should import pymongo and use MongoClient without errors:

enter image description here

Related