Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create MongoDb Database with Python

Tags:

python

mongodb

I try to create database with simple Python code and It does not work.

When I try to create database, I cant see my database name in python and MongoDb.

Also, When I create database in MongoDb I can see my database name in Python. My Python version is 3.6

Can you help me please ?

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")

mydb = client["mydatabase"]

print(client.list_database_names())
like image 218
Cemalettin Altınsoy Avatar asked Jan 29 '26 19:01

Cemalettin Altınsoy


1 Answers

The new database isn't created until you do your first insert.

Try adding an insert like below (also creating a collection) and you should see your new db.

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")

mydb = client["mydatabase"]  # you can also use dot notation client.mydatabase
mydb.mycoll.insert_one({"test": 'test'})
print(client.list_database_names())

The database mydatabase is output in the list of database names.

like image 97
DaveStSomeWhere Avatar answered Jan 31 '26 09:01

DaveStSomeWhere