Q:

Select random document with filter with pymongo?

I found, that to select random document, I need to use $sample command:
// Get one random document from the mycoll collection.
db.mycoll.aggregate(
   { $sample: { size: 1 } }
)

but what if I need to filter documents and THEN take random one?
I am processing documents, which are not processed yet with
query = {'start_time': {'$exists': False}}
hp_entries = mongo.hyperparameters_collection.find(query)

How would I do with random?

A:

As any other aggregation stage it takes input from the previous stage.
Prepend the $sample with $match to filter the documents. E.g.:
db.hyperparameters_collection.aggregate([
    { "$match": { "start_time": { "$exists": False } } },
    { "$sample": { "size": 1 } }
])

