【问题标题】:query using date that stored as string in mongodb in spring mongo data使用在spring mongo数据中存储为字符串的日期查询
【发布时间】:2019-11-25 17:42:33
【问题描述】:

下面是我的代码 -

MatchOperation match_Status_Count = new MatchOperation(
                Criteria.where("date1").gte("2019-3-25T17:34:24.734Z").andOperator(
                        Criteria.where("date1").lte("2019-11-25T17:34:24.734Z")
                                ));
        GroupOperation group_Status_Count = Aggregation.group("Status").count().as("Statuscount");
        Aggregation aggregate_Status_Count = Aggregation
                .newAggregation(match_Status_Count, group_Status_Count)
                .withOptions(new AggregationOptions(false, false,
                        new BasicDBObject(new Document().append("batchSize", 100000000000L))));
        ;
        AggregationResults<ARStructData> orderAggregate_Status_Count = mongoTemplate
                .aggregate(aggregate_Status_Count, D_AR_COLLECTION_NAME, ARStructData.class);

由于日期存储为字符串,因此根据字符串gte和lte返回。 如果有人给我解决方案,我们将不胜感激。

【问题讨论】:

  • 所以您希望能够说“给我两个日期之间的文档,其中输入日期是实际日期对象,但文档中的日期是字符串”?
  • 现在输入日期不是实际的日期对象,而只是字符串。但是修改它也不起作用。是的,文档中的日期是一个字符串

标签: mongodb spring-boot spring-mongodb


【解决方案1】:

假设您输入的日期是字符串,您需要将它们转换为 java.util.Date 例如

Date lowerDate = yourFavoriteCvtDateStringtoDate(lowerDateString);
Date upperDate = yourFavoriteCvtDateStringtoDate(upperDateString);

然后创建一个查询,利用$toDate 函数将文档中的日期字符串转换为可比较的真实日期(此处为便于查看的Javascript):

db.foo.aggregate([
{$addFields: {X: {$toDate: "$date1"} }}
,{$match: {$and: [ {"X": {$gt: lowerDate}}, {"X": {$lt: upperDate}} ] }}
                       ]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 2023-04-08
    • 2021-02-26
    • 2019-08-17
    相关资源
    最近更新 更多