在mongodb按日期分组?

时间:2018-04-09 11:06:33

标签: node.js mongodb mongoose mongodb-query aggregation-framework

我有使用createdAt字段的评论模式

{
    "_id" : ObjectId("5acafcf834d81a1650a35b8c"),
    "createdAt" : ISODate("2018-04-09T05:41:12.228Z"),
    "author" : ObjectId("5ac8ba3582c2345af70d4658"),
    "comment" : "rgeregfedsagvdfsae",
}
{
    "_id" : ObjectId("5acafcee34d81a1650a35b8b"),
    "createdAt" : ISODate("2018-04-09T05:41:02.992Z"),
    "author" : ObjectId("5ac8ba3582c2345af70d4658"),
    "comment" : "dsfsfdssfdsfdsf",
}
{
    "_id" : ObjectId("5acb024134d81a1650a35b8d"),
    "createdAt" : ISODate("2018-04-10T06:03:45.625Z"),
    "author" : ObjectId("5ac8ba3582c2345af70d4658"),
    "comment" : "dsfdsafdafsdf",
}

我想按createdAt进行分组......这应该是我的输出

    [ { createdAt: '2018-04-09', numberOfComments: 2 },
      { createdAt: '2018-04-10', numberOfComments: 1 } ]

我试过这个......

const CommentsCount = await Comment.aggregate([
        {
          $project:
          {
            month: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } },
          }
        },
        {
          $group: {
            _id: '$month'
          }
        }
      ])

给出[ { _id: '2018-04-09' }, { _id: '2018-04-10' } ]

2 个答案:

答案 0 :(得分:1)

db.comment.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $project: {
                createdAt: {
                    $dateToString: {
                        format: "%Y-%m-%d",
                        date: "$createdAt"
                    }
                },
                author: 1,
                comment: 1

            }
        },

        // Stage 2
        {
            $group: {
                _id: {
                    createdAt: '$createdAt'
                },
                comments: {
                    $sum: 1
                }
            }
        },

        // Stage 3
        {
            $project: {
                createdAt: '$_id.createdAt',
                numberOfComments: '$comments',
                _id: 0
            }
        }

    ]


);

答案 1 :(得分:0)

使用$addFields运算符

db.collection_name.aggregate([
    {
        $project:
        {
            month: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } },
        }
    },
    {
        $group: {
            _id: { createdAt: "$month"},
            numberOfComments: { $sum: 1 }
        }
    },

    {
        $addFields: {
            createdAt: "$_id.createdAt"
        }
    },
    {
        $project: {
            _id: false
        }
    }
]);