选择带有pymongo过滤器的随机文档?

时间:2017-11-21 17:31:07

标签: mongodb python-3.x pymongo

found, that to select random document,我需要使用$sample命令:

// Get one random document from the mycoll collection.
db.mycoll.aggregate(
   { $sample: { size: 1 } }
)

但如果我需要过滤文件然后随机抽取一下该怎么办?

我正在处理尚未使用

处理的文档
query = {'start_time': {'$exists': False}}
hp_entries = mongo.hyperparameters_collection.find(query)

我如何使用随机?

1 个答案:

答案 0 :(得分:3)

与任何其他聚合阶段一样,它接受前一阶段的输入。

$sample前加上$match来过滤文档。 E.g:

db.hyperparameters_collection.aggregate([
    { "$match": { "start_time": { "$exists": False } } },
    { "$sample": { "size": 1 } }
])