Random Field Filter for MongoDB Documents

  • Share this:

Code introduction


This function filters documents from a MongoDB collection based on a randomly selected field and value, and returns a list of matching documents.


Technology Stack : MongoDB, pymongo

Code Type : Database query

Code Difficulty : Intermediate


                
                    
def random_document_filter(collection, field, value):
    """
    This function filters documents from a MongoDB collection based on a given field and value.
    It is a simple example of querying a MongoDB collection using pymongo.
    """
    from pymongo import MongoClient
    import random
    
    # Connect to MongoDB
    client = MongoClient('localhost', 27017)
    db = client['test_database']
    
    # Randomly select a field and value to filter
    fields = list(collection.find_one())
    field = random.choice(list(fields.keys()))
    value = random.choice(list(fields[field]))
    
    # Filter documents
    filtered_documents = collection.find({field: value})
    
    # Close the connection
    client.close()
    
    return list(filtered_documents)