【问题标题】:Is it possible to count distinct Documents in MongoTemplate?是否可以在 MongoTemplate 中计算不同的文档?
【发布时间】:2021-05-28 16:27:13
【问题描述】:

是否可以在 mongoTemplate 中以某种方式链接 distinct(...) 和 countDocuments(...)。

类似的东西

mongoTemplate.getCollection("foo").distinct("bar", Foo.class).countDocuments();

请记住,我将有几百万个结果,所以我不想通过将所有不同的实体放入一个数组然后获取它的大小来在 jvm 中造成瓶颈。我宁愿从 MongoDB 中获取一个数字,而不要打扰 JVM。

【问题讨论】:

  • 您可以使用into(new ArrayList<Foo>()).size() 而不是countDocuments。这会给你计数。
  • 问题是,我预计会有几百万个结果,这意味着我的数组将在 JVM 中膨胀。是否可以从 MongoDB 获取大小而不是获取数组的大小?
  • 这里是否允许使用 mongo 的聚合管道?您能否提供有关 bar 属性架构的更多信息

标签: mongodb spring-boot spring-data-mongodb mongotemplate


【解决方案1】:

是的,可以使用 mongoTemplate 获取不同文档的数量。

Mongo shell 查询

db.foo.aggregate([{
    $group: {
        _id: "$bar"
    }
}, {
    $count: "total"
}]);

这个查询的输出将是

{
    "total" : 8
}

使用 MongoTemplate 得到这个结果:

GroupOperation groupOperation = Aggregation.group("bar");
CountOperation countOperation = Aggregation.count().as("total");
Aggregation aggregation = Aggregation.newAggregation(groupOperation, countOperation);

Document result = mongoTemplate.aggregate(aggregation, "foo", Document.class)
        .getUniqueMappedResult();
Integer total = Objects.nonNull(result) ? result.getInteger("total") : 0;

【讨论】:

  • 这正是我需要的!谢谢
【解决方案2】:

我记得上次我使用Aggregation Pipeline Operators 对集合进行分组(这将为您提供不同的值),然后在它上面使用count()

例如:

Aggregation pipeline = newAggregation(
        group(fields("foo","bar")),
        group("_id.bar").count().as("distinctCount")
    ); 

否则使用以下一种衬里:

return mongoTemplate.aggregate(aggregation,Class.COLLECTION_NAME,BasicDBObject.class).getMappedResult();
// in this case make sure this function's return type is Integer or Long not int or long

注意:在这种情况下,请确保函数的返回类型是 IntegerLong 而不是 intlong,因为 int 和 long 是原始数据类型并且它们不包含 null。但是,如果没有数据,聚合逻辑可能会返回 null,因此使用 Long 或 Integer(对象可能为 null)

【讨论】:

    【解决方案3】:

    您可以将 Mongo Aggregate 与 $group 一起使用。

    db.foo.aggregate([{
      '$group': {
        '_id': '_id', 
        'count': {
        '$sum': 1
       }
      }]);
    

    你会得到:

    { "_id":"_id", "count":12}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-28
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多