You should have installed and started MongoDB server, if you didn't yet, go to MongoDB.

Install MongoDB client driver for Python

I suggest using pip install command , like this:

pip install pymongo

Connect to MongoDB server with pymongo

For default network port and local server instance , just single line of code to connect MongoDB .

import pymongo
import time
from pprint import pprint
from pymongo import MongoClient
client = MongoClient()

Select database and collection

In MongoDB's flexible schema, databases, collections and fields are created on the fly. They are created when being referenced.

db = client.test
collection =

Insert data into MongoDB database

A collection can store any kind of JSON like documents. But the best practice is to store the same kind of data into collection.{
    'title' : 'article title',
    'date' : int(time.time()),
    'content' : 'article content'
    'title' : 'article title',
    'date' : int(time.time()),
    'content' : 'article content',
    'author' : 'name'

Notice how the time is retrieved, in Python, time.time() returns a floating number which represent the seconds, weird but just discard the number after dot is what we want.

Modify the data

Use the $set operator to modify document.

collection.update({'title' : 'article title'},{'$set' : {'author' : 'James'}})

Using find to query data

Query by field value. Find documments with author 'James'.

result = collection.find({"author" : "Jones"})
for x in result:    
    pprint (x)

Find range with conditions.

result = collection.find({"date" : {
    '$lt' : int(time.time()) - ( 3 * 60 * 60)

Find with regular expression. Find documents with field value start with 'm'.

result = collection.find({ "title" :  {
    '$regex' : '^m'

Sort result by date.

result = collection.find({'author' : 'James'}).sort("date", pymongo.DESCENDING)

Delete document

Delete has the same syntax with find, the method is remove.

collection.remove({"title" : {
    '$regex' : '^m'