代码之家  ›  专栏  ›  技术社区  ›  Subburaj

GroupBy日期+mongodb

  •  0
  • Subburaj  · 技术社区  · 7 年前

    我必须根据给定文档的月份来汇总结果。请将以下内容作为我的文档:

    {
        "_id" : ObjectId("5b3314a12b05b1b247366f48"),
        "email" : "abc@gmail.com",
        "qwerty":[{
                "id" : "5ba4ebbad1b5eaf038841302",
                "status" : "inprogress",           
                "Date" : "2018-08-20"
            }, 
            {
                "id" : "5ba4ebbad1b5eaf038841303",
                "status" : "inprogress",           
                "Date" : "2018-08-20"
            }]
    

    以下是我的疑问:

    var query =[
            { $match: {"email":email} },
            {$unwind: "$courses" },
            {$group:{_id:{$substrCP: ["$qwerty.Date", 5, 2]},count:{$sum:1}}}
        ];
    

    它工作正常。但我 $substrCP: ["$qwerty.Date", 5, 2] 基于日期格式是“2018-08-20”,如果是“2018-08-20”呢??因此,可以将上述查询更改为适应nay类型。

    我也试过用新的 Date("").getMonth() 但它显示为“南”,我知道这是不可能使用组内。

    请提出你的意见。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Akrion    7 年前

    你可以利用 $month 结合 $dateFromString 要获得您需要的:

    db.collection.aggregate([
      {
        $match: {
          "email": "abc@gmail.com"
        }
      },
      {
        $unwind: "$qwerty"
      },
      {
        $group: {
          _id: {
            $month: {
              $dateFromString: {
                dateString: "$qwerty.Date"
              }
            }
          },
          count: {
            $sum: 1
          }
        }
      }
    ])
    

    你可以 see it here

    要按日期分组,您可以不使用 $month :

    db.collection.aggregate([
      {
        $match: {
          "email": "abc@gmail.com"
        }
      },
      {
        $unwind: "$qwerty"
      },
      {
        $group: {
          _id: {
            $dateFromString: {
              dateString: "$qwerty.Date"
            }
          },
          count: {
            $sum: 1
          }
        }
      }
    ])
    

    查看此版本 here