9

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?

Dims
  • 47,675
  • 117
  • 331
  • 600

1 Answers1

9

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 } }
])
rnorris
  • 1,571
  • 2
  • 17
  • 23
Alex Blex
  • 34,704
  • 7
  • 48
  • 75