如何在MongoDB中按周对文档进行分组 [英] How to group by documents by week in mongodb

查看:250
本文介绍了如何在MongoDB中按周对文档进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{
     "_id" : ObjectId("568b650543712795bf864a45"),
    "companyId" : "55e2d7cfdc8f74d14f5c900f",
    "timeStamp" : ISODate("2014-12-03T18:30:00.000Z")
},
{
    "_id" : ObjectId("568b650543712795bf864a49"),

    "companyId" : "55e2d7cfdc8f74d14f5c900f",
    "timeStamp" : ISODate("2014-12-04T18:30:00.000Z")
}

如何在mongodb中按星期对文档进行分组.我需要按最近7周对文档进行分组,并且周分组应基于文档中的"timeStamp"字段.

解决方案

您可以通过使用聚合操作来实现. mongodb中有$ week 聚合操作. /p>

首先使用您使用的任何编程语言确定startDate.

在以下管道操作中,计算每周匹配的文档数.您可以在所需的任何字段/类型的聚合中进行此操作.

pipeline = [
    {
        $match: {
            timeStamp: {$gt: ISODate(startDate)},
        }
    },
    {
        $group: {
            _id: {$week: '$timeStamp'},
            documentCount: {$sum: 1}
        }
    }
];
db.mycollection.aggregate(pipeline)

对于您指定的上述两个文档,结果将为

{ "_id" : 48, "documentCount" : 2 }

上面的_id说,是第48周,有两个文档.

通过链接$ week 转到知道mongodb如何计算星期数.

{
     "_id" : ObjectId("568b650543712795bf864a45"),
    "companyId" : "55e2d7cfdc8f74d14f5c900f",
    "timeStamp" : ISODate("2014-12-03T18:30:00.000Z")
},
{
    "_id" : ObjectId("568b650543712795bf864a49"),

    "companyId" : "55e2d7cfdc8f74d14f5c900f",
    "timeStamp" : ISODate("2014-12-04T18:30:00.000Z")
}

how to group by documents by week in mongodb. i need to get document grouped by last 7 weeks and week grouping should be on the basis of "timeStamp" field in the document.

解决方案

You can achieve this by using the aggregate operation. There is $week aggregation operation in mongodb.

First determine the startDate using whatever programming language you use.

In following pipeline operation, counting the number of documents matching a week. You may do it on any field/type of aggregation you needed.

pipeline = [
    {
        $match: {
            timeStamp: {$gt: ISODate(startDate)},
        }
    },
    {
        $group: {
            _id: {$week: '$timeStamp'},
            documentCount: {$sum: 1}
        }
    }
];
db.mycollection.aggregate(pipeline)

For the above two documents you specified the result will be

{ "_id" : 48, "documentCount" : 2 }

The _id above says, 48th week, and there are two documents.

Go through the link $week to know how mongodb counts the week numbers.

这篇关于如何在MongoDB中按周对文档进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆