mongodb - MongoDB sorting by date as type String
问题描述
Can someone help me with the query for sorting an array by date in ascending order? I have tried the below query but the sorting is not happening as expected,
db.getCollection(xyz).aggregate([{
$match: {
"_id":{$in:[{"a" : "NA","b" : "HXYZ","c" : "12345","d" : "AA"}]}
}
},{
$sort: {'bal.date': 1}
},
{ $project: {
balances: { $slice: ["$bal",2]}
}
}
])
My collection:
/* 1 */
{
"_id" : {
"a" : "NA",
"b" : "HXYZ",
"c" : "12345",
"d" : "AA"
},
"bal" : [
{
"type" : "E",
"date" : "2015-08-02"
},
{
"type" : "E",
"date" : "2015-08-01"
},
{
"type" : "E",
"date" : "2015-07-07"
}
]
}
Please help me what is the problem in the above query. Thanks in advance.
解决方案
你正在$match
与$sort
舞台混合
使用聚合管道阶段的正确语法
db.collection.aggregate([
{ "$match": {
"_id": {
"$eq": {
"a": "NA",
"b": "HXYZ",
"c": "12345",
"d": "AA"
}
}
}},
{ "$unwind": "$bal" },
{ "$sort": { "bal.date": 1 }},
{ "$group": {
"_id": "$_id",
"bal": {
"$push": "$bal"
}
}}
])
推荐阅读
- postgresql - 为什么 PostgreSQL 为当前正在执行的命令的文本保留固定数量的内存?
- react-native - 无法访问 SD 卡(ExternalStorageDirectoryPath 指向 /storage/emulated/0)
- swift - SwiftUI - Embedded UITextField invokes the shouldChangeCharacters delegate method for suggested text
- linux - How to input non-alphabetic letters (such as Chinese, Japanese, Korean) in unix/linux console without X running
- android - How to remove the launcher icon in android 10(Q)
- mysql - ordering in sql result
- python - How can I fix this error with sklearn.preprocessing?
- java - ButterKnife is not binding views and causing exceptions
- php - 如何计算在PHP中的时隙数组中传递的时间
- python - 如何将 Flask.route 与 Flask 一起使用