Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

85
Views
Mongoose how to count unique days in a month?

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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


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

    }
);
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!