【问题标题】:Mongo Template Difference between days and compare with db fieldMongo模板天数之间的差异并与db字段进行比较
【发布时间】:2021-10-19 13:27:15
【问题描述】:

我在 db 中有如下方式的文档,我希望减去当前日期,得到天数的差异,并将差异与存储在 db 中的值作为同一文档中的有效性进行比较。

所以我的查询应该获取所有 startDate 和当前日期差大于有效性的文档

//mongo document snap
{
  "campaignDuration": {         
    "startDate": {
      "$date": "2021-10-21T11:39:59.657Z"
    },
  },
  "attributes":{
    "validity":2
  }
}

有人可以帮我在春季使用 mongo 模板进行查询

【问题讨论】:

    标签: java spring mongodb date mongotemplate


    【解决方案1】:

    试试这个:

    db.collection.aggregate([
       {
          $match: {
             $expr: {
                $gte: [
                   {
                      $dateDiff: {
                         startDate: "$$NOW",
                         endDate: "$startDate",
                         unit: "day"
                      }
                   },
                   "$attributes.validity"
                ]
             }
          }
       }
    ])
    

    $dateDiff 是 MongoDB 5.0 版中新引入的。如果您运行旧版本,请将表达式替换为 {$multiply: [{$subtract: ["$startDate", "$$NOW"]}, 1000*60*60*24]}

    【讨论】:

    • 我是 mongo 的新手,你能帮我使用与上面等效的 spring mongo 模板吗
    • 对不起,我不熟悉Java或spring
    【解决方案2】:

    我根据上面 Wernfried Domscheit 的回答 (https://stackoverflow.com/a/69632053/7009165) 编写了 spring mongo 模板

    AggregationOperation matchOperation = (context) -> {
                Document matchDocument = new Document("$expr", new Document("$gte",
                        Arrays.asList(
                                new Document("$dateDiff", new Document()
                                        .append("startDate", "$$NOW")
                                        .append("endDate", "$startDate")
                                        .append("unit", "day")),
                                "$attributes.validity"
                        )));
                return new Document("$match", matchDocument);
            };
    mongoTemplate.aggregate(Aggregation.newAggregation(matchOperation), "collection", OutputClass.class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-01
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      • 2011-05-06
      • 2021-02-04
      • 1970-01-01
      相关资源
      最近更新 更多