如何在Mongoose/NodeJS的时间戳字段中计算不同的日期项目? [英] How to count distinct date items in a timestamp field in Mongoose/NodeJS?

查看:359
本文介绍了如何在Mongoose/NodeJS的时间戳字段中计算不同的日期项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在NodeJS中使用Mongoose,并且有一个包含如下文档的集合-

I use Mongoose in my NodeJS, and I have a collection with documents that look like this -

var SomeSchema = new Schema({
    date: {
        type: Date,
        default: new Date()
    },
    some_item: {
        type: String
    }
});

date字段包含带有时间成分的日期(例如,2014-05-09 09:43:02.478Z).如何获得给定日期(例如2014-05-08)的不同项目?

The date field contains date with the time component (for example, 2014-05-09 09:43:02.478Z). How do I get a count of distinct items for a given date, say 2014-05-08?

编辑:理想情况下,我希望获得每个不同日期的记录数.

Ideally, I would like to get a count of records for each distinct date.

推荐答案

您想要的是将聚合框架与

What you want is usage of the aggregation framework with the aggregate() command, at least for finding one date as you ask:

SomeSchema.aggregate(
    [
        { "$match": {
            "date": { 
                "$gte": new Date("2014-05-08"), "$lt": new Date("2014-05-09")
            }
        }},
        { "$group": {
            "_id": "$some_item",
            "count": { "$sum": 1 }
        }}
    ],
    function(err,result) {
        // do something with result

    }
);

如果您要特别搜索多个日期的计数",则可以执行以下操作:

If you are specifically looking for "counts" over several dates then you can do something like this:

SomeSchema.aggregate(
    [
        { "$match": {
            "date": { 
                "$gte": new Date("2014-05-01"), "$lt": new Date("2014-06-01")
            }
        }},
        { "$group": {
            "_id": { 
                "year":  { "$year": "$date" },
                "month": { "$month": "$date" },
                "day":   { "$dayOfMonth": "$date" }
            }
            "count": { "$sum": 1 }
        }}
    ],
    function(err,result) {
        // do something with result

    }
);

这使您可以每天"分组.如果您希望使用日期聚合运算符,请在文档中查找这进一步.

And that gives you "per day" grouping. Look for the date aggregation operators in the documentation if you wish to take this further.

这篇关于如何在Mongoose/NodeJS的时间戳字段中计算不同的日期项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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