简体   繁体   English

MongoDB Java API-如何将样本聚合与查找查询结合在一起?

[英]MongoDB Java API - How to combine sample aggregation with a find query?

I need to get a randomized sample of documents in a collection with a find criteria. 我需要在具有find条件的集合中获取文档的随机样本。

Bson sample = com.mongodb.client.model.Aggregates.sample(size);
BasicDBObject query = new BasicDBObject().append("myKey", value);

How can I combine this sample aggregation with the find query? 如何将这种sample聚合与find查询结合在一起?

You can use aggregation with $match followed by $sample . 您可以在$match之后使用$sample来使用聚合。

import static com.mongodb.client.model.Aggregates.*;
import static com.mongodb.client.model.Filters.*;
import static java.util.Arrays.asList;

Bson match = match(eq("myKey", value));
Bson sample = sample(size);
collection.aggregate(asList(match, sample));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM