Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 509
Dims Avatar asked Nov 21 '17 17:11

Dims


1 Answers

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 } }
])
like image 106
Alex Blex Avatar answered Sep 27 '22 00:09

Alex Blex