Home > other >  Mongoose how to count unique days in a month?
Mongoose how to count unique days in a month?

Time:05-31

i am working on a problem where in my database there supposed to be multiple entries from day to day. each entry includes a timestamp. the problem is im supposed to find how many days in each month a data has been entered. ex: if a user sends a message every 2 days in may. my answer would be: "the user used the message function for 15 days in may". now if the user sends 5 messages every 2 days in may. the answer would be still 15. im only counting the days the user has been using the app.

using this query:

model.find({ 
    date: {
        $gte: new Date(startOfMonth), 
        $lt: new Date(endOfMonth)
    }
})

i was able to find all data entries on a specific month. the data may look like something like this:

 Date: dd/mm/yy        Message:
 1/5/2022              "Hello"
 1/5/2022              "World"
 1/5/2022              "!"
 5/5/2022              "Hello World!"
 8/5/2022              "Hello World!"

the desired answer would be 3 unique days in may.

How do i achieve this using mongodb? the simplest answer that come to mind is to use additional queries to group by unique days, but i have no idea how to do that using mongo provided i need to access the date.

CodePudding user response:

You can use distinct
db.collection.distinct({date:{$gte:new Date(startOfMonth),$lt:new Date(endOfMonth)}}).length
if you are directly storing the date of it.

Note : This may not work if you're storing complete timestamp instead of date.

CodePudding user response:

This might solves your problem. it will return distinct messages.


Model.aggregate(
    [
        { "$match": {
            "date": { 
                "$gte": new Date(startOfMonth), "$lt": new Date(endOfMonth)
            }
        }},
        { "$group": {
            "_id": "$Message",
            "count": { "$sum": 1 }
        }}
    ],
    function(err,result) {
        // do something with result

    }
);
  • Related