簡體   English   中英

MongoDB查詢組集合按上周/月/所有NodeJS日期的日期

[英]MongoDB query group collection by date last week/month/all NodeJS

我需要統計所有用戶,即上周和上個月的用戶,按日期分組。

我試過了

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數據。 僅包含用於測試的對象的必要屬性

[{
    "_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版本:

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"}]
}})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM