You can download this code by clicking the button below.
This code is now available for download.
This function randomly retrieves a document from a MongoDB collection that matches the specified query conditions. If no query conditions are provided, it retrieves one document from all documents.
Technology Stack : PyMongoEngine, MongoDB, PyMongo
Code Type : PyMongoEngine query function
Code Difficulty : Intermediate
def get_random_document(collection, query=None):
from pymongo import ASCENDING
from mongoengine import Q
import random
if query is None:
query = Q()
cursor = collection.objects(query=query).order_by(ASCENDING)
if cursor.count() == 0:
return None
return random.choice(list(cursor))