按Mongo上的日期字符串(升序)排序

时间:2014-07-17 08:52:34

标签: php mongodb

我有一个数据库,其日期列的格式为dd / mm / yyyy,我想按日期按升序排序。

$cursor = $collection->find($filter)->sort(array('date' => 1, 'tripID' => 1));

日期是一个字符串,我也在对tripID进行过滤,但这方面是有效的。问题是目前我得到了:

01/01/2014
01/02/2014
02/01/2014
02/02/2014

我想要的是:

01/01/2014
02/01/2014
01/02/2014
02/02/2014

是否可以使用查询实现此目的,还是需要在应用程序中完成?

1 个答案:

答案 0 :(得分:0)

假设我们在您的问题中给出了列表

> db.dates.insertMany([{ "date": "01/01/2014" },
    { "date": "01/02/2014" },
    { "date": "02/01/2014" },
    { "date": "02/02/2014" }])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5a314eae330cc13d0c9b10c4"),
                ObjectId("5a314eae330cc13d0c9b10c5"),
                ObjectId("5a314eae330cc13d0c9b10c6"),
                ObjectId("5a314eae330cc13d0c9b10c7")
        ]
}

在MongoDB 3.6中,我们可以使用聚合框架并使用$dateFromStringhttps://docs.mongodb.com/manual/reference/operator/aggregation/dateFromString/)管道运算符将字符串日期转换为日期,然后对值进行排序:

> db.dates.aggregate([
    { "$project" : { "date" : { "$dateFromString" : { "dateString" : "$date"} } } },
    { "$sort" : { "date" : 1 } }
    ])
{ "_id" : ObjectId("5a314eae330cc13d0c9b10c4"), "date" : ISODate("2014-01-01T00:00:00Z") }
{ "_id" : ObjectId("5a314eae330cc13d0c9b10c5"), "date" : ISODate("2014-01-02T00:00:00Z") }
{ "_id" : ObjectId("5a314eae330cc13d0c9b10c6"), "date" : ISODate("2014-02-01T00:00:00Z") }
{ "_id" : ObjectId("5a314eae330cc13d0c9b10c7"), "date" : ISODate("2014-02-02T00:00:00Z") }

Pior to MongoDB 3.6有一种解决方法可以将您的字符串转换为词汇字符串日期:

> db.dates.aggregate([
    { "$project" : {
        "date" : {
            "$let" : {
                "vars" : { "parts":{ "$split" : [ "$date", "/" ] } },
                "in" : {
                    "$concat" : [
                        { "$arrayElemAt" : [ "$$parts" , 2 ] },
                        "-",
                        { "$arrayElemAt" : [ "$$parts", 1 ] },
                        "-",
                        { "$arrayElemAt" : [ "$$parts", 0 ] } ]
                    }
                }
            }
        }
    },
    { "$sort" : { "date" : 1 } }
])

{ "_id" : ObjectId("5a314eae330cc13d0c9b10c4"), "date" : "2014-01-01" }
{ "_id" : ObjectId("5a314eae330cc13d0c9b10c6"), "date" : "2014-01-02" }
{ "_id" : ObjectId("5a314eae330cc13d0c9b10c5"), "date" : "2014-02-01" }
{ "_id" : ObjectId("5a314eae330cc13d0c9b10c7"), "date" : "2014-02-02" }

我知道这是用javascript而你提到它是在php中,但它实际上是相同的,检查php文档(http://php.net/manual/en/mongocollection.aggregate.php