问题
I find out the aggregate framework, but how to get the doucments in a month or a week? I am tring to calculate how many orders are placed in a week or in a month. The documents are like this:
{
"_id" : ObjectId("53834167b54a3b22f0079e2c"),
"createdDate" : ISODate("2014-05-26T13:28:07.942Z"),
"__v" : 0
},
{
"_id" : ObjectId("53834167b54a3b22f0079e2c"),
"createdDate" : ISODate("2014-05-28T09:28:07.942Z"),
"__v" : 0
}
All I want to have is how many orders are placed in a month according the createdDate.
The current code I am using:
Order.aggregate([
{ "$match": {
'createdDate': {
"$gte": new Date("2014-05-25"), "$lte": new Date("2014-05-27")
}
}},
{ "$group": {
"_id": { "$dayOfYear": "$createdDate" },
"totalCost": { "$sum": "$totalCost" },
"sum": {"$sum": 1}
}}
],
function(err, result) {
console.log(result);
if (err) {
res.send(400, err);
} else {
res.send(200, result);
}
});
回答1:
If you just want the total orders within a time period then you can just use a range query on your date using $gte and $lt style operators:
var query = Model.find({
"createdDate": {
"$gte": new Date("2014-05-21"), "$lte": new Date("2014-05-29")
}
}).count()
query.exec(function(err, count) {
And that will just return the count if documents found within that range.
If you want to sum a value from inside your document, or even indeed retrieve something like "daily totals" from within that date range then you can use the aggregation framework to do this:
Model.aggregate([
{ "$match": {
"$gte": new Date("2014-05-21"), "$lte": new Date("2014-05-29")
}},
{ "$group": {
"_id": { "$dayOfYear": "$createdDate" }
"totalValue": { "$sum": "$orderTotal" }
}}
],
function(err, result) {
That not only makes use of the $sum operator to add up the values for our "orderTotal" field, but also makes use of a date aggregation operator to group on all values as each single day within the given range.
If that last case is what you want you can use various operators there to break up various date periods that you want contain within your results.
来源:https://stackoverflow.com/questions/23928680/node-js-mongoose-js-how-to-get-sum-of-orders-are-placed-in-a-month-or-a-week