关于java:mongo随机获取N条数据

mongo 命令随机抽样

db.attachment_extract_status.aggregate( [ { $sample: { size: 500 }},{$match:{extract_status:1}} ] )

mongoTemplete随机抽样

@Test
public void test_sample()  {
    Aggregation aggregation =
            Aggregation.newAggregation(
                    Aggregation.match(Criteria.where("extract_status").is(1)),
 Aggregation.sample(1000));
 AggregationResults<JSONObject> outputTypeCount =
            mongoTemplate.aggregate(aggregation, "attachment_extract_status", JSONObject.class);
 for (Iterator<JSONObject> iterator = outputTypeCount.iterator(); iterator.hasNext(); ) {
        System.out.println(iterator.next().getLong("content_id"));
 }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理