可以在mongodb中比较日期字符串吗? [英] Possible to compare date strings in mongodb?

查看:1793
本文介绍了可以在mongodb中比较日期字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含带有日期属性的文档的集合,如下所示:

I have a collection that contains documents with a date attribute like so:

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

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

I would like to select records that were created on a certain day. I was hoping I could use toDateString() and compare the values but when I do a search like the one below:

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

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

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

But this does not work. Is there any way to do what I am attempting above?

推荐答案

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

If you want to select records then use a date range:

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

然后选择包含在两个日期之间的所有小时,分钟等.

And that selects all the contained hours, minutes etc, falling between the two dates.

因此,您应该尝试使用日期值,而不要强制输入字符串.

So you should be trying to use the date values and not coerce into strings.

如果您希望通过此操作进行汇总,或者需要以仅一天"的格式运行结果,则可以使用操作员:

If you want this for doing aggregation or otherwise need the results in a day only format then do this using $project and the date 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
    }}
])

这篇关于可以在mongodb中比较日期字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆