MongoDB按日期查询组集合上周/上月/所有NodeJS [英] MongoDB query group collection by date last week/month/all NodeJS

查看:47
本文介绍了MongoDB按日期查询组集合上周/上月/所有NodeJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要统计所有用户,上周和上个月的用户,按日期分组.

I need to count all users, users from last week and last month, grouping by date.

我试过了

var project = {
    $project:{
        day: { $dayOfMonth: "$updatedAt" },
        month: { $month: "$updatedAt" },
        year: { $year: "$updatedAt" }
    }
},
group = {   
    "$group": { 
        "_id": { 
            "date": "$updatedAt",
        },  
        "count" : { "$sum" : "$1" }
    }
};

db.collection.aggregate([project, group])...

我需要结果看起来像

{lastWeek: 12, lastMonth: 20, all: 102}

编辑添加了示例 json 数据.仅包含用于测试的对象的必要属性

EDIT added sample json data. Included only necessary properties of objects for testing

[{
    "_id" : ObjectId("someId"),
    "createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
    "updatedAt" : ISODate("2018-01-08T09:51:55.460Z"),
    "foo1" : null
},{
    "_id" : ObjectId("someId"),
    "createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
    "updatedAt" : ISODate("2017-12-30T09:51:55.460Z"),
    "foo1" : null
},{
    "_id" : ObjectId("someId"),
    "createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
    "updatedAt" : ISODate("2018-01-17T09:51:55.460Z"),
    "foo1" : null
},{
    "_id" : ObjectId("someId"),
    "createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
    "updatedAt" : ISODate("2018-01-01T09:51:55.460Z"),
    "foo1" : null
},{
    "_id" : ObjectId("someId"),
    "createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
    "updatedAt" : ISODate("2017-04-08T09:51:55.460Z"),
    "foo1" : null
}]

推荐答案

你可以试试下面的聚合

var today = new Date();
var lastWeek = new Date();
today.setDate(today.getDate() - 7);
var lastMonthFromToday = new Date();
lastMonthFromToday.setMonth(today.getMonth() - 1);

db.col.aggregate(
{"$group":{
    "_id":null,
    "lastWeek":{"$sum":{"$cond":[{$and:[{"$gte":["$updatedAt",lastWeek]}, {"$lte":["$updatedAt",today]}]}, 1, 0]}},
    "lastMonth":{"$sum":{"$cond":[{$and:[{"$gte":["$updatedAt",lastMonthFromToday]}, {"$lte":["$updatedAt",today]}]}, 1, 0]}},
    "all":{"$sum":1}
}})

Mongo 3.4 版本:

Mongo 3.4 version:

db.col.aggregate(
{"$facet":{
  "lastWeek":[{"$match":{"updatedAt":{"$gte":lastWeek, "$lte":today}}},{"$count":"count"}],
  "lastMonth":[{"$match":{"updatedAt":{"$gte":lastMonthFromToday, "$lte":today}}},{"$count":"count"}],
  "all":[{"$count":"count"}]
}})

这篇关于MongoDB按日期查询组集合上周/上月/所有NodeJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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