【问题标题】:Find Max Value in MongoDB by Using Spring Data MongoDb使用 Spring Data MongoDb 在 MongoDB 中查找最大值
【发布时间】:2022-01-10 12:05:39
【问题描述】:

其实我需要从 TABLE 中找到 select MAX(lastUpdatedTime)

我在做:

TableRepositoryImpl.java

*maxTime(){
Query query= new Query().limit(1).with(Sort.by(Sort.Direction.DESC, "lastUpdatedTime"))
return mongoTemplate.findOne(query, TABLE.class)
}*

但是这种排序方法需要额外的时间,有人知道如何像我们在sql中那样使用MAX函数来实现吗?或任何其他优化方式,我只需要在我的 mongoDB 中找到最新更新的时间戳

【问题讨论】:

    标签: mongodb spring-data spring-data-mongodb


    【解决方案1】:

    您可以使用$max 聚合:

    [
      {
        "_id": 1,
        "item": "abc",
        "price": 10,
        "quantity": 2,
        "date": ISODate("2014-01-01T08:00:00Z")
      },
      {
        "_id": 2,
        "item": "jkl",
        "price": 20,
        "quantity": 1,
        "date": ISODate("2014-02-03T09:00:00Z")
      },
      {
        "_id": 3,
        "item": "xyz",
        "price": 5,
        "quantity": 5,
        "date": ISODate("2014-02-03T09:05:00Z")
      },
      {
        "_id": 4,
        "item": "abc",
        "price": 10,
        "quantity": 10,
        "date": ISODate("2014-02-15T08:00:00Z")
      },
      {
        "_id": 5,
        "item": "xyz",
        "price": 5,
        "quantity": 10,
        "date": ISODate("2014-02-15T09:05:00Z")
      }
    ]
    
    db.collection.aggregate({
      $group: {
        _id: null,
        max: {
          $max: "$date"
        }
      }
    })
    

    返回date的最大值:

    [
      {
        "_id": null,
        "max": ISODate("2014-02-15T09:05:00Z")
      }
    ]
    

    【讨论】:

    • 嘿,但是我们如何在java代码中实现它
    【解决方案2】:

    试试

    GroupOperation groupMaxOperation = Aggregation.group().max("lastUpdatedTime").as("maxLastUpdatedTime");
    
    AggregationResults<Document> aggregate = mongoTemplate.aggregate(Aggregation.newAggregation(groupMaxOperation), TABLE.class, Document.class);
    
    Optional<Date> maxLastUpdatedTime = Optional.ofNullable(aggregate.getUniqueMappedResult())
                    .map(result -> result.get("maxLastUpdatedTime", Date.class));
    

    如果 mongo 集合(TABLE)很大,您可能需要将 allowDiskUse 添加到聚合中

    AggregationResults<Document> aggregate = mongoOps.aggregate(Aggregation.newAggregation(groupMaxOperation)
                            .withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build()),
                    TABLE.class, Document.class);
    

    【讨论】:

      猜你喜欢
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 2014-04-13
      相关资源
      最近更新 更多