Extracting data from MongoDB using Python and pyMongo

Use the Python Package Installer (pip3) to install the pyMongo package:

% pip3 install pyMongo
Collecting pyMongo
  Downloading https://files.pythonhosted.org/packages/5e/25/372cc21c6ad318356fa819ca9b5bf021b747cd5a00b868c1db1e3e8fe228/pymongo-3.10.1-cp38-cp38-macosx_10_9_x86_64.whl (351kB)
     |████████████████████████████████| 358kB 1.1MB/s 
Installing collected packages: pyMongo
Successfully installed pyMongo-3.10.1

This simple example show how to connect to MongoDB from Python 3 using pyMongo. It reads all documents from the development db in the transactions collection and writes them to a CSV file named transactions.csv.

from pymongo import MongoClient
import csv
from decimal import Decimal

TWO_PLACES = Decimal(10) ** -2

client = MongoClient()

db = client['development']

collection = db['transactions']

cursor = collection.find()

with open('transactions.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC)
    for doc in cursor:
        account_id = doc['accountId']
        desc = doc['description']
        amount = Decimal(doc['amount']).quantize(TWO_PLACES)
        currency = (doc['currency'])
        date_created = doc['dateCreated']
        writer.writerow([account_id, desc, amount, currency, date_created])

The output in transactions.csv will be as follows: –

"A00000001","Bowers & Wilkins P5 Headphones",299.00,"GBP","2020-02-09 14:30:00"
"A00000001","Apple Homepod",329.00,"GBP","2020-02-09 15:30:00"
"A00000002","AAA Batteries",12.00,"GBP","2020-02-09 15:35:00"