[MongoDB] How to connect MongoDB with Python

Hi all, after I installed python on linux, as I wrote in this article, how to install Python on Linux, this time I’m going to show how to connect mongoDB with python.
ENVIRONMENT
- Ubuntu 18.04 LTS
- Python 2.7.17
How to to connect DB
You have to create a new file with connection_test.py and insert the code below. After, in order to run the code, you can write in command line: python3 connection_test.py
import pymongo
# pprint library is used to make the output look more pretty
from pprint import pprint
# connect to MongoDB, change the << MONGODB URL >>
to reflect your own connection string
client = pymongo.MongoClient('localhost',27017)
db=client.admin
# Issue the serverStatus command and print the results
serverStatusResult=db.command("serverStatus")
pprint(serverStatusResult)
$ python3 connection_test.py
How to insert user
import pymongo
client=pymongo.MongoClient('localhost',27017)
blogDatabase=client["blog"]
usersCollection = blogDatabase["users"]
usersCollection.insert_one(
{
"username":"frodo",
"password":"frodo",
"lang":"IT"})
user=usersCollection.find_one()
print(user)
articlesCollection = blogDatabase["articles"]
author = "frodo"
article = {
"title": "the lord of the rings",
"body" : "rings, hobbit",
"author": author,
"tags" : ["frodo", "Tolkien","italy"]
}
if usersCollection.find_one( {"username" : author }) :
articlesCollection.insert_one( article )
else:
raise ValueError ("Author %s does not exist" % author )
$ python3 insert_user.py
How to create article
import pymongo
client = pymongo.MongoClient('localhost',27017)
blogDatabase = client["blog"]
articlesCollection = blogDatabase["articles"]
author = "frodo"
article = {
"title": "Silmarillion",
"body" : "legend",
"author": author,
"tags" : ["frodo", "Tolkien","italy"]
}
if usersCollection.find_one( {"username" : author }) :
articlesCollection.insert_one( article )
else:
raise ValueError ("Author %s does not exist" % author )
$ python3 create_article.py
How to insert articles
import pymongo
import string
import datetime
import random
def randomString( size, letters = string.ascii_lowercase ):
return ''.join( [ random.choice ( letters ) for i in range (size) ] )
client = pymongo.MongoClient('localhost',27017)
def makeArticle ( count, author, timestamp ) :
return {
"_id" : count,
"title" : randomString( 20 ),
"body" : randomString( 80 ),
"author" : author,
"postdate" : timestamp }
def makeUser (username ) :
return {
"username" : username,
"password" : randomString ( 10 ),
"karma" : random.randint(0, 500),
"lang" : "IT"
}
blogDatabase = client["blog"]
usersCollection = blogDatabase["users"]
articlesCollection = blogDatabase["articles"]
bulkUsers = usersCollection.initialize_ordered_bulk_op()
bulkArticles = articlesCollection.initialize_ordered_bulk_op()
ts = datetime.datetime.now()
for i in range (1000000 ) :
username ="USER_" + str( i )
bulkUsers.insert( makeUser (username ) )
ts = ts + datetime.timedelta( seconds = 1 )
bulkArticles.insert ( makeArticle( i, username, ts ))
if ( i % 500 == 0 ) :
bulkUsers.execute()
bulkArticles.execute()
bulkUsers = usersCollection.initialize_order_bulk_op()
bulkArticles = articlesCollection.initialize_ordered_bulk_op()
bulkUsers.execute()
bulkArticles.execute()
$ python3 insert_articles.py
Thank you for your attention. Stay Tuned!