Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a new database in MongoDB using PyMongo?

Can I create a new database simply by connecting to the MongoDB server, or is there another way to create it using Python? If so, how is this done?

like image 697
J.Olufsen Avatar asked Dec 19 '11 19:12

J.Olufsen


People also ask

How do you create a collection in PyMongo?

from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] #Creating a collection collection = db['example'] print("Collection created........")

Is PyMongo the same as MongoDB?

What is PyMongo? PyMongo is MongoDB's official native driver for Python. It's a library that lets you connect to a MongoDB database and query the data stored using the MongoDB Query API.


2 Answers

MongoDB creates databases and collections automatically for you if they don't exist already.

For using python library with MongoDB, check out this documentation.

Warning: the example is based on Pymongo 2.1. If you're using Pymongo 3.4, check this doc.

from pymongo import Connection connection = Connection() db = connection['test-database'] collection = db['test-collection'] 

So here you can use any name for database and collection.

like image 155
DarthVader Avatar answered Oct 08 '22 06:10

DarthVader


This is Mongodb 3.4 Version:

from pymongo import MongoClient client = MongoClient() db = client.primer coll = db.dataset 

neither the database nor the collection are created until you attempt to write a document.

Document: Python Driver (PyMongo)

like image 23
宏杰李 Avatar answered Oct 08 '22 06:10

宏杰李