Hackerss.com

hackerss
hackerss

Posted on

Connect to mongodb in Python

Connect to mongodb - Python:


#import pymongo
from pymongo import MongoClient

#connect to mongodb
client = MongoClient('localhost', 27017)

#create a database
db = client.test_database

#create a collection
collection = db.test_collection

#insert a document
collection.insert_one({'name': 'Raj', 'age': 25})

#insert multiple documents
collection.insert_many([{'name': 'Raj', 'age': 25}, {'name': 'Raj', 'age': 25}])

#find all documents in the collection
cursor = collection.find()
for document in cursor:
    print(document)



Enter fullscreen mode Exit fullscreen mode

Top comments (0)