Random Document Fetcher from MongoDB Collection

  • Share this:

Code introduction


This function fetches a random document from a specified MongoDB collection. It first connects to the local MongoDB instance, then queries the specified collection, and uses the $sample aggregation operation to randomly select a document.


Technology Stack : MongoDB, PyMongo, $sample aggregation operation

Code Type : Database query

Code Difficulty : Intermediate


                
                    
import pymongo
from pymongo import MongoClient
from bson.objectid import ObjectId

def fetch_random_document(collection_name):
    client = MongoClient('localhost', 27017)
    db = client['mydatabase']
    collection = db[collection_name]
    
    # Fetch a random document from the specified collection
    random_document = collection.aggregate([{"$sample": {"size": 1}}])[0]
    
    # Close the connection to the database
    client.close()
    
    return random_document