【问题标题】:Possible to compare date strings in mongodb?可以比较MongoDB中的日期字符串吗?
【发布时间】:2023-03-17 20:51:02
【问题描述】:

我有一个包含具有如下日期属性的文档的集合:

{
   title: "whatever",
   created: ISODate("2013-05-27T03:36:50Z")
}

我想选择在某一天创建的记录。我希望我可以使用toDateString() 并比较这些值,但是当我进行如下搜索时:

db.myCollection.find({ 'created.toDateString()': new Date('05/27/2013').toDateString() }).pretty()

但这不起作用。有什么办法可以做我上面尝试的事情吗?

【问题讨论】:

    标签: javascript mongodb mongodb-query aggregation-framework


    【解决方案1】:

    如果要选择记录,请使用日期范围:

    db.collection.find({
        created: { "$gte": new Date("2013-05-27"), "$lt": new Date("2013-05-28") }
    })
    

    这会选择两个日期之间包含的所有小时、分钟等。

    所以您应该尝试使用日期值而不是强制转换为字符串。

    如果您希望此操作用于聚合或以其他方式需要仅以一天格式显示结果,请使用$project 和日期operators 执行此操作:

    db.collection.aggregate([
        // Still match on the normal date forms, this time whole month
        { "$match": {
            created: { 
               "$gte": new Date("2013-05-01"), 
               "$lt": new Date("2013-05-31") 
            }
        }},
    
        // Project the date
        { "$project": {
            "date": {
                "year"  : { "$year"  : "$created" },
                "month" : { "$month" : "$created" },
                "day":  : { "$dayOfMonth": "$created" }
            },
            "title": 1
        }},
    
        // Group on day and title
        { "$group": {
            "_id": {
                "date"  : "$date",
                "title" : "$title"
            },
            "count": { "$sum": 1 }
        }},
    
        // Sort by date
        { "$sort": { 
            "_id.date.year": 1,
            "_id.date.month": 1,
            "_id.date.day": 1,
        }},
    
        // Project nicer dates and document
        { "$project": {
            "_id": 0,
            "date": { "$concat": [
                { "$substr": [ "$_id.date.year", 0, 4 ] },
                "-",
                { "$substr": [ "$_id.date.month", 0, 2 ] },
                "-",
                { "$substr": [ "$_id.date.day", 0, 2 ] }
            ]},
            "title": "$_id.title",
            "count": 1
        }}
    ])
    

    【讨论】:

    • 感谢尼尔提供的信息。我可以问为什么我“......应该尝试使用日期值而不是强制转换为字符串”?
    • @AbeMiessler 这通常不是一个好主意,因为强制涉及成本。除非使用 $where,否则您尝试使用 find 的操作将不起作用,这将强制进行表扫描,并减慢执行 JavaScript 的速度。最后,如两个示例中所示,没有必要。唯一有效的情况是最终投影,但没有理由不能在代码中完成该部分。始终使用日期。
    • 谢谢!仅供参考 - 日期投影中的日期字段后有两个冒号。
    猜你喜欢
    • 2021-06-18
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 2015-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多