說我們有你的問題給出的列表
> 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,我們可以使用聚合框架和使用$dateFromString
(https://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到MongoDB的3.6有你的字符串轉換爲字符串lexicial日期解決方法:
> 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,但它是pratically相同,結賬PHP文檔(http://php.net/manual/en/mongocollection.aggregate.php)
您應該將字符串轉換到MongoDB的日期,它是你必須什麼無論如何,在應用程序中。最大的問題是這裏的琴絃並不是按照順序排列的。 –