【问题标题】:Compare string date in mongoose with Date.now() or new Date()将猫鼬中的字符串日期与 Date.now() 或 new Date() 进行比较
【发布时间】:2019-12-19 17:19:32
【问题描述】:

我在 MongoDB 中保存了一个字符串日期,如下所示:'19 Dec 2019'。我想用 new Date() 获取所有匹配的日期,即当前日期。

Mongo 存储日期:

db_date: '2019 年 12 月 18 日'

。将此日期与当前日期匹配,我们使用

当前日期:新日期();

并返回一个匹配数组。

Model.find() ???

【问题讨论】:

    标签: javascript node.js mongodb date mongoose


    【解决方案1】:

    请试试这个:

    db.yourCollectionName.aggregate([{
        $addFields: {
            /** converting month from string to num :: Dec to 12 & extracting date & year from string */
            month: {
                $indexOfArray: [[, "Jan", "Feb", "Mar", "Aprl", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]
                    , { $arrayElemAt: [{ $split: ['$db_date', " "] }, 1] }]
            }
            , date: { $toInt: { $arrayElemAt: [{ $split: ['$db_date', " "] }, 0] } }, year: { $toInt: { $arrayElemAt: [{ $split: ['$db_date', " "] }, 2] } }
        }
    }, {
        /** db_date is being converted to format ISODate() from parts year + month + day & then to this : "2019-12-18" */
        $addFields: {
            db_date: {
                $dateToString: {
                    format: "%Y-%m-%d", date: {
                        $dateFromParts: {
                            'year': '$year', 'month': '$month', 'day': '$date'
                        }
                    }
                }
            }
        }
    }, { $project: { 'month': 0, 'year': 0, 'date': 0 } },
    {
        /** Here we're converting ISODate() from input to like this : "2019-12-19", This is what you actually asked for */
        $match: {
            $expr: {
                $eq: ['$db_date', {
                    $dateToString: {
                        format: "%Y-%m-%d", date: new Date()
                    }
                }]
            }
        }
    }
    ])
    

    此查询应该可以帮助您获得所需的结果,但在我看来,进行这种转换是一项艰巨的任务,您通常可以通过在数据库设计时考虑您的事务然后将数据存储在DB 根据您的阅读要求,如果不是 - 以另一种方式,可以通过将代码中的输入转换为与存储在 DB 中的数据匹配来简化您的 DB!

    【讨论】:

    • 也不确定你到底想要什么,因为new Date() 会给你类似ISODate("2019-12-19T22:49:11.502Z") 的正确日期,即使我们将'18 Dec 2019' 转换为ISODate() - 比较这两个不会虽然日期不匹配,但时间不匹配,所以我们将输入请求转换为2019-12-19 && 还将字段值存储为2019-12-19,这样给定日期的所有文档都匹配!!
    猜你喜欢
    • 2019-04-20
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多