logo
down
shadow

MongoDB : Adding Days field to Date Type Field in DB and then comparing with the current date


MongoDB : Adding Days field to Date Type Field in DB and then comparing with the current date

By : user2948969
Date : November 15 2020, 06:54 AM
fixed the issue. Will look into that further This really is one of those cases where you have to make a stand and get something changed rather than try to "jump through hoops" to deal with the poor design decisions of someone else. The "olive branch" to extend here is that the initial design may have well not taken into consideration how the data was going to be used.
The query you are proposing without changing how the data is stored requires no small amount of effort. I'm leaving everything here in "shell" form with JSON notation or otherwise the raw JavaScript. JSON is easy to parse or translate to the methods available to construct BSON objects for the Java driver as with other languages.
code :
{ "contractDate" : ISODate("2014-04-23T00:00:00Z"), "term" : 10 }
{ "contractDate" : ISODate("2014-04-23T00:00:00Z"), "term" : 7 }
{ "contractDate" : ISODate("2014-11-30T00:00:00Z"), "term" : 1 }
db.expiring.count({
  "$where": function () {

    var now = new Date(),
        today = new Date(
          now.valueOf() -
          ( now.valueOf() % ( 1000 * 60 * 60 * 24 ) )
        );

    var adjustedMonth =
      this.contractDate.getMonth() + 1 + this.term;

    var year = ( adjustedMonth > 12 ) ?
      this.contractDate.getFullYear() + 1
      : this.contractDate.getFullYear();

    var month = ( adjustedMonth > 12 ) ?
      adjustedMonth - 12 : adjustedMonth;

    var day = this.contractDate.getDate();

    var expiring = new Date( year + "-" + month + "-" + day );
    return expiring > today;
  }
})
db.expiring.aggregate([
  { "$project": {
    "contractDate": 1,
    "term": 1,
    "expires": {
      "year": {
        "$cond": [
          { "$gt": [ 
            { "$add": [{ "$month": "$contractDate" }, "$term" ] },
            12
          ]},
          { "$add": [{ "$year": "$contractDate" }, 1 ] },
          { "$year": "$contractDate" }
        ]
      },
      "month": {
        "$cond": [
          { "$gt": [
            { "$add": [{ "$month": "$contractDate" }, "$term" ] },
            12
          ]},
          { "$subtract": [
            { "$add": [{ "$month": "$contractDate" }, "$term" ] },
            12
          ]},
          { "$add": [{ "$month": "$contractDate" }, "$term" ] }
        ]
      },
      "day": { "$dayOfMonth": "$contractDate" }
    }
  }},
  { "$group": {
    "_id": null,
    "count": {
      "$sum": {
        "$cond": [
          { "$or": [
             { "$gt": [ "$expires.year", thisYear ] },
             { "$and": [
               { "$eq": [ "$expires.year", thisYear ] },
               { "$gt": [ "$expires.month", thisMonth ] },
             ]},
             { "$and": [
               { "$eq": [ "$expires.year", thisYear ] },
               { "$eq": [ "$expires.month", thisMonth ] },
               { "$gt": [ "$expires.day", thisDay ] }     
             ]}
          ]},
          1,
          0
        ]
      }
    }
  }}
])
{ 
    "contractDate" : ISODate("2014-04-23T00:00:00Z"), 
    "term" : 10,
    "expiry": ISODate("2015-02-23T00:00:00Z") 
}
{ 
    "contractDate" : ISODate("2014-04-23T00:00:00Z"), 
    "term" : 7,
    "expiry" : ISODate("2014-11-23T00:00:00Z"),         
}
{ 
    "contractDate" : ISODate("2014-11-30T00:00:00Z"),
    "term" : 1,
    "expiry": ISODate("2014-12-30T00:00:00Z")
}
db.expiring.count({ "expiry": { "$gt": new Date("2014-12-30") } })


Share : facebook icon twitter icon
How to find number of days between a field date and current date using php

How to find number of days between a field date and current date using php


By : Adam Noscov
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Your $start is not an object of DateTime class in the second example, so of course it does not work. How is the date stored? Technically this might work, but it is highly dependent on what this $demurage2['DC_date'] value is.
code :
$start=new DateTime($demurage2['DC_date']);
Comparing datetime field in python, not just date or time , Type Error :Can't compare unicode to date.datetime field

Comparing datetime field in python, not just date or time , Type Error :Can't compare unicode to date.datetime field


By : Kristians Jaunzems
Date : March 29 2020, 07:55 AM
should help you out Use attributes in form.cleaned_data to compare. Attributes in cleaned_data will be of appropriate data type.
e.g.
code :
if form.is_valid():
   if form.cleaned_data['time']==datetime.datetime.min:
   ....
Number of days between current date and date field

Number of days between current date and date field


By : Migasa
Date : March 29 2020, 07:55 AM
this will help You can use STR_TO_DATE():
code :
SELECT DATEDIFF(CURDATE(),STR_TO_DATE(date, '%m/%d/%Y')) AS days
FROM table1
MongoDB Query: How to add some days to a date field before comparing it with a given date

MongoDB Query: How to add some days to a date field before comparing it with a given date


By : user2782740
Date : March 29 2020, 07:55 AM
seems to work fine You can't. A simple query in MongoDB can't use values from the document it's querying. You can only use values that are constant throughout the query.
Valid Query:
code :
{
    FirstName : "bar"
}
{
    FirstName : LastName
}
MongoDB Delete records with date field less than days from another field

MongoDB Delete records with date field less than days from another field


By : Jonathon Brook
Date : March 29 2020, 07:55 AM
it should still fix some issue The Bad News is you cant really do that in one query.
You will have to first "calculate" the new field and then use the documents that matched and call a remove operator, this can be done fairly easily using an aggregation by subtracting from the date and matching documents with a negative result.
Related Posts Related Posts :
  • es lint '' is assigned a value but never used' eventhough i have used it
  • Can "name" attribute be used for custom VueJS components
  • Get innerHTML of content when it is clicked
  • HTTPS causes CSS animations to not load? Very confused
  • How to hide other div apart from touched div to the band
  • Is global variable assignment atomic on NodeJS?
  • Datepicker onchangemonthyear beforeshowday
  • trying to render html files using jade but it still adresses it as a jade
  • Google Analytics - Understanding and Dissecting the Snippet: What is | | [ ];
  • Replacing "[aA09.b]." to "[aA09.b]\n" in in JavaScript
  • Why wrap a function definition in an immediate function?
  • Enable / disable jQuery script on switching to different tab in a HTML page
  • how can find return variable value outside anonymous function in node js mysql query function
  • Converting 1 to 0001 in javascript array
  • svg viewbox should not resize the text fontSize?
  • store newline character with string in a variable
  • MP4 videos in Flowplayer does not play in Windows 7 Chrome
  • jquery focusin event not firing
  • How to debug Vue application with google chrome
  • html 5 web app cache download complete javascript alert?
  • Ember.js setupController fired only once
  • How to validate a currency input
  • How to convert my Array of data to key & value pair
  • Statistics circles in CSS
  • So I wanted to make a trig solver in javascript?
  • Showing HighCharts series name on x-axis and in legend
  • In Rails, how can we pass parameters in script?
  • Build Fails: `npm rebuild node-sass --force`
  • Angular Datepicker change dateformat
  • Trying to extract data from between two sets of characters
  • Configuring Jest in WebStorm
  • Uncaught Error: Syntax error, unrecognized expression: tr.ec_portfolio_title,
  • JQuery fading in fading out continuously
  • Unexpected end of input (Line 1) and Undefined Function?
  • How to animate the width of a div slowly with jquery
  • JavaScript + RegEx Complications- Searching Strings Not Containing SubString
  • SignalR - Unable to get property 'client' of undefined or null reference
  • full calendar not displaying when loaded (with backbone)
  • Angular: Update service and share data between controllers
  • ReplaceAll Google script
  • Search for matching LI items in separate UL
  • Access arguments of an... argument
  • Customizing Google custom search jsapi (query strings)
  • React | Can´t load Images > Module not found
  • Dynamically creating buttons in DOJO
  • 404 Not Found in AJAX post call
  • How do I find out, using javascript, what software opened and running my application?
  • Javascript to check the status of wireless connection
  • StarDict support for JavaScript and a Firefox OS App
  • Phonegap event Resume
  • call javascript function on ENTER key press?
  • When is the best time to remove no-js classes from the html tag
  • Recommended email sending languages
  • setInterval not working properly with chrome
  • Does IE create new scope for each script tag?
  • Uncaught SyntaxError: Unexpected token < Underscore and parse issues
  • How to pass captured URL to Email Body in HTML
  • How to structure default nested resources?
  • Store all the keys of a JSON object in a variable
  • Need an efficient way to group the Array of object in javascript
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org