问题
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
}
});
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
?
EDIT: Ideally, I would like to get a count of records for each distinct date.
回答1:
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.
来源:https://stackoverflow.com/questions/23563289/how-to-count-distinct-date-items-in-a-timestamp-field-in-mongoose-nodejs