Get Number of WeekDays Month Wise - mongodb

I am new to Mongo DB. Can anyone help me in how to get the number of weekdays between two Given dates in month wise.
$dayOfWeek of a date will give the value of the date 1 for sunday and 7 for saturday.
But my question is how can i increment the date from start date to end date to find the number of weekdays.
Sample Data:
db.data.insert({"startDate":ISODate('2016-01-01'), "endDate":ISODate('2016-03-31')})
WriteResult({ "nInserted" : 1 })
> db.data.find().pretty()
{
"_id" : ObjectId("57c6e6a6a1e49d654caca17a"),
"startDate" : ISODate("2016-01-01T00:00:00Z"),
"endDate" : ISODate("2016-03-31T00:00:00Z")
}
Now need to find the number of Weekdays between the Start Date (2016-01-01) and End Date (2016-03-31).
With output giving Jan:21,Feb:21,Mar:23.
Please suggest for an solution...

Related

i am not getting data till today date in mongodb using $gte

what i want is to get the users who have created there account in between the range of dates and also want to get the customer with order count greater then 1 for those new customers, so what i am doing is trying to get the data greater then the last month i.e 1st of march 2020 but the output is giving me users till 1 april, why not till today i.e 11 april, the data is in following format
"_id" : ObjectId("1dv47sd1a10048521sa1234d"),
"updatedAt" : ISODate("2020-04-01T16:19:26.460+05:30"),
"createdAt" : ISODate("2020-04-01T16:18:46.066+05:30"),
"email" : "edx#gmail.com",
"phone" : "xxxxxxxxxx",
"password" : "$awdad$2b$10$4YaO6AEZqXA9ba0iz14ALi",
"dob" : "00/20/1990",
"stripeID" : "xxxxxxxxxxxxxxxx",
"__t" : "Customer",
"banned" : false,
"picture" : "link to image",
"name" : {
"first" : "ababab",
"last" : "Saaa"
},
"orderCount" : 2,
"creditCards" : [ ],
"addresses" : [ ],
"__v" : 0,
"isEmailVerified" : true
i have written a query for extracting data from the date greater then last month but it is giving me data till the 1 of april, my query is as follows
db.users.find({
"createdAt" : { "$gte" :new Date("2020-03-1") }
})
so i want to get data timm today from 1 march 2020 also order count is greter then 1,thanks in advance i am preety new with mongo
MongoDB only stores absolute times (aka timestamps or datetimes), not dates. As such the queries should generally be specified using times, not dates, also.
Furthermore, MongoDB always stores times in UTC. Different systems can operate in different timezones. For example, the shell may be operating in a different timezone from your application.
To query using dates:
Determine what timezone the dates are in.
Convert dates to times in that timezone. For example, 2020-03-01 00:00:00 UTC - 2020-03-31 23:59:59 UTC and 2020-03-01 00:00:00 -0400 - 2020-03-31 23:59:59 -0400 are both "March" and would match different sets of documents.
Convert the times to UTC. This may be something that a framework or library you are using handles for you, for example Mongoid in Ruby does this.
Use the UTC times to construct MongoDB queries.
This is stated in the documentation here.

MongoDB $dateToString format expression %G strange behaviour

I have a document that has the following property amongst others
{
dueDate: ISODate("2019-12-29T13:00:00.000Z")
}
I'm building an aggregation, and in the $project stage, I am attempting the following:
"utcDueDate": "$dueDate",
"rawDueDate" : {
"$dateToString" : {
"date" : "$dueDate",
"timezone" : "Australia/Sydney"
}
},
"prettyDueDate" : {
"$dateToString" : {
"date" : "$dueDate",
"format" : "%d/%m/%G",
"timezone" : "Australia/Sydney"
}
}
I am expecting the following output:
utcDueDate: 2019-12-29T13:00:00.000Z
rawDueDate: 2019-12-30T00:00:00.000Z
prettyDueDate: 30/12/2019
However, I am getting 30/12/2020 for prettyDueDate.
If I use %Y instead of %G it works as expected.
%G is meant to be the ISO standard format for year (0000-9999). I am using mongo version 4.0.13
Can anyone please explain why this is happening? Quite a few aggregations that are used for reporting have this format string and I'd really like to avoid having to change them all
This is expected behavior for %G since it is using a 'week numbered year' calendar.
There is a very detailed explanation of this behavior here. I've copied a small piece of the explanation below:
The phrase "ISO 8601 format" in the documentation refers to a way of
specifying dates that breaks them up by week number and day number
instead of the traditional month and day. Years in this format always
begin on Monday, so on years where December 31 is not a Sunday, it
gets treated as being part of the next year by the ISO 8601 calendar.

MongoDB query to retrieve distinct documents by date

I have documents in the database with a dateTime value like so:
{
"_id" : ObjectId("5a66fa22d29dbd0001521023"),
"exportSuccessful" : true,
"month" : 0,
"week" : 4,
"weekDay" : "Mon",
"dateTime" : ISODate("2018-01-22T09:02:26.525Z"),
"__v" : 0
}
I'd like to:
query the database for a given date and have it return the document that contains the dateTime if the date matches (I don't care about the time). This is mainly to test before inserting a document that there isn't already one for this date. In the above example, if my given date is 2018-01-22 I'd like the document to be returned.
retrieve all documents with a distinct date from the database (again, I don't care about the time portion). If there are two documents with the same date (but different times), just return the first one.
From what I understand Mongo's ISODate type does not allow me to store only a date, it will always have to be a dateTime value. And on my side, I don't have control over what goes in the database.
Try range query with start date time from start of the day to end date time to end of the day. So basically create dates a day apart.
Something like
var start = moment().utc().startOf('day');
var end = moment().utc().endOf('day');
db.collection.find({
dateTime: {
$gte: start,
$lte: end
}
})
Get all distinct dates documents:
db.collection.aggregate(
{"$group":{
"_id":{
"$dateToString":{"format":"%Y-%m-%d","date":"$dateTime"}
},
"first":{
"$first":"$$ROOT"
}
}}])

Not getting accurate result in mongodb using gte and lte query

This is my user collection in mongodb
{
"_id" : NumberLong(104060),
"age" : 41,
"username" : "appubhai75#gmail.com",
"roles" : [
"ROLE_USER"
],
"firstName" : "Apurva",
"lastName" : "Shah",
"email" : "appubhai75#gmail.com",
"createdDate" : ISODate("2016-02-08T12:23:02.001Z"),
}
i am using criteria like this
criteria = new Criteria().orOperator(name, email)
.andOperator(genderCriteria).and("_id").ne(id).and("createdDate").gte(startDate).lte(endDate);
when i am passing startdate and enddate like:
Start date is::2015-12-16T00:00:00.000+05:30
end date is::2016-02-08T00:00:00.000+05:30
this user is not coming ,but when i change my enddate to
end date is::2016-02-09T00:00:00.000+05:30
then it is coming.
If i am using gte and lte then it must include the date equal to also .Like,when i pass the date from 16 dec to 8 feb, then it is giving all the users with created date 16 to 7 feb. not including the user with created date 8 feb,and when i am passing 16 dec to 9 feb then it include 8 feb user.Is anything am doing wrong i am confuse.Please help.
Thank you.
You won't get results for this
Start date is::2015-12-16T00:00:00.000+05:30
end date is::2016-02-08T00:00:00.000+05:30
Check the created Date for user it is ISODate("2016-02-08T12:23:02.001Z") date is equal but not the time.Overall your user date is not in your range .Mongo it checks for both date and time equality.
The one solution you can have is at your application side add additional time 24*60*60 - 1 to this Date createdDate using DateUtils in org.apache.commons.lang.time(Apache Commons Lang)
DateUtils.addSeconds(createdDate,24*60*60-1);
Important Assuming that you will send only date in request.You have to add above code to pre proprocess your request object but not when your inserting.When ever a request comes add this piece of code.It will work fine

MongoDB Aggregation Framework Date NOW

I am attempting to perform a calculation in an aggregation based on the day of the current month. For example, I want to divide the total number of transactions by the day of the month to get transactions per day.
The problem is I can't figure out how to get the current date. I see plenty of examples where it's hardcoded, but what I need is more like the MySQL NOW() function.
I've tried something like this:
> db.statistics.aggregate([{$project: {dayofmonth: {$dayOfMonth: Date()}}}])
{
"errmsg" : "exception: can't convert from BSON type String to Date",
"code" : 16006,
"ok" : 0
}
But that produces the error you see.
How can I get the current day of the current month for use in an aggregation calculation?
You almost did it. You have to write new Date()
db.statistics.aggregate([
{$project: {dayofmonth: {$dayOfMonth: new Date()}}}
])
it will produce results like this:
{
"result" : [
{
"_id" : "statisctiId",
"dayofmonth" : 9
}
}