2

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.

3
  • As per mongoose documentation . Model.distinct(field, conditions, callback); Commented May 9, 2014 at 11:46
  • What would my conditions be? Commented May 9, 2014 at 11:51
  • 1
    Distinct is not a good idea. It is just a wrapper around mapReduce and therefore runs a lot slower than the aggregation framework alternative. Commented May 9, 2014 at 11:53

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Fantastic. Will I be able to do this for all unique dates too? Or would I have to select each date in a loop and then count distinct records for that date?
Good answer. Neil, you forgot your _id definition in your second example.
@JohnnyHK Thankyou, Thankyou once again. How are you not a moderator yet?
@GPX I think there is an edit in there that shows how to find singular day boundaries and group by them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.