首页 > 解决方案 > 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.

标签: mongodb

解决方案


你正在$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"
    }
  }}
])

推荐阅读