Query A MongoDB Collection For Documents Using Python And PyMongo


  • MongoDB stores data as documents in the format of BSON -in other words the binary JSON.
  • A MongoDB server can host multiple Mongo Databases.
  • Each MongoDB database can hold multiple MongoDB collections. Each collection of a MongoDB can hold multiple MongoDB documents. Each document is like a record and each collection is like a table.
  • The MongoDB overview explains the details of installing MongoDB, the Python Client library for MongoDB - PyMongo and creating documents, collections and databases.
  • This article explains how to retrieve a set of documents from a MongoDB collection using PyMongo, which is the Python driver for MongoDB.

Querying a set of documents from a MongoDB collection:

  • Import the Python module MongoDB.
  • Create a MongoClient instance by passing the hostname and the port number of the MongoDB server.
  • From the MongoClient instance obtain a database instance by specifying the database name either by object.attribute notation of by using the dictionary[subscript] notation.
  • Get a collection instance from the database.
  • Call the find() method on the collection instance and iterate through printing each result. Invoking find() without passing any argument will return all the documents present in the MongoDB collection.

Query MongoDB using PyMongo from a Python Program


# import the MongoClient module

from pymongo import MongoClient


# Create a client instance of MongoClient

client      = MongoClient('mongodb://localhost:27017/')


# Get the database object

# Here name of the database is "sample"

db          = client.sample


# Get the collection object

# Here name of the database is "states"

collection  = db.states


# Make a query to list all the documents

for doc in collection.find():

    #Print each document




{'_id': ObjectId('5ab4eb8667425860a27ed87a'), 'county1': ['county1', 'county2', 'county3'], 'state': 'State Name', 'capital': 'capital city'}

{'_id': ObjectId('5ab4eb8667425860a27ed87b'), 'county2': ['county1', 'county2', 'county3'], 'state': 'State Name', 'capital': 'capital city'}

{'_id': ObjectId('5ab4eb8667425860a27ed87c'), 'county3': ['county1', 'county2', 'county3'], 'state': 'State Name', 'capital': 'capital city'}


Copyright 2022 © pythontic.com