MongoDb Date

Date()

Returns a date either as a string or as a Date object.

- Date() returns the current date as a string in mongosh.
- new Date() returns the current date as a Date object. mongosh wraps the Date object with the ISODate helper. The ISODate is in UTC.

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats:

new Date("") returns the ISODate with the specified date.
new Date("") specifies the datetime in the client's local timezone and returns the ISODate with the specified datetime in UTC.
new Date("") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
new Date() specifies the datetime as milliseconds since the UNIX epoch (Jan 1, 1970), and returns the resulting ISODate instance.

Behavior
Internally, Date objects are stored as a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970).

Return Date as a String
To return the date as a string, use the Date() method, as in the following example:

var myDateString = Date();
//Wed Dec 19 2012 01:03:25 GMT-0500 (EST)

typeof myDateString – The operation returns string.

Return Date as Date Object
mongosh wraps objects of Date type with the ISODate helper; however, the objects remain of type Date.

The following example uses new Date() to return Date object with the specified UTC datetime.

var myDate = new Date();
var myDateInitUsingISODateWrapper = ISODate();
myDate instanceof Date
myDateInitUsingISODateWrapper instanceof Date

The operation returns true for both.

In Mongodb I am storing date and time in ISODate format.
Which looks like this

ISODate("2012-07-14T01:00:00+01:00")

< Using nodejs/javascript, how can I display the time component so I would get something like this Time : 01:00

foo = new Date("2012-07-14T01:00:00+01:00")
Sat, 14 Jul 2012 00:00:00 GMT
foo.toTimeString()
'17:00:00 GMT-0700 (MST)'

MongoDB’s ISODate() is just a helper function that wraps a JavaScript date object and makes it easier to work with ISO date strings.

You can still use all of the same methods as working with a normal JS Date, such as:

ISODate("2012-07-14T01:00:00+01:00").toLocaleTimeString()

// Note that getHours() and getMinutes() do not include leading 0s for single digit #s

ISODate("2012-07-14T01:00:00+01:00").getHours()
ISODate("2012-07-14T01:00:00+01:00").getMinutes()

Date query with ISODate in mongodb doesn’t seem to work

Although $date is a part of MongoDB Extended JSON and that’s what you get as default with mongoexport I don’t think you can really use it as a part of the query.

If try exact search with $date like below:

db.foo.find({dt: {"$date": "2012-01-01T15:00:00.000Z"}})

you’ll get error:

error: { "$err" : "invalid operator: $date", "code" : 10068 }

Try this:

db.mycollection.find({
    "dt" : {"$gte": new Date("2013-10-01T00:00:00.000Z")}
})

or

db.mycollection.find({
    "dt" : {"$gte": ISODate("2013-10-01T00:00:00.000Z")}
})

ISODate may be also required to compare dates without time.

The mongo shell provides various methods to return the date, either as a string or as a Date object:

- Date() method which returns the current date as a string.
- new Date() constructor which returns a Date object using the ISODate() wrapper.
- ISODate() constructor which returns a Date object using the ISODate() wrapper.

Aggregation Methods with Date

/*|
db.monthlyBudget.insertMany([
    { "_id": 1, "category": "food", "budget": 400, "spent": 450 },
    { "_id": 2, "category": "drinks", "budget": 100, "spent": 150 },
    { "_id": 3, "category": "clothes", "budget": 100, "spent": 50 },
    { "_id": 4, "category": "misc", "budget": 500, "spent": 300 },
    { "_id": 5, "category": "travel", "budget": 200, "spent": 650 }
])
*/

var result = db.monthlyBudget.find( { $expr: { $gt: [ "$spent" , "$budget" ] } } ).toArray()[0]
printjson(result)

retult.forEach((elem)=>{
    printjson(elem)
})

var path;
db.getCollection('monthlyBudget', function(err, collection) {
    collection.find({}).toArray(function(err, results) {
        path = results;
        console.log(results);
    });
});



db.sales.insert([
{
   "_id" : 1,
   "item" : "abc",
   "price" : 20,
   "quantity" : 5,
   "date" : ISODate("2017-05-20T10:24:51.303Z")
}
])


db.sales.aggregate([
    {
        $project: {
            "nycHour": {
                $hour: { date: "$date", timezone: "-05:00" }
            }
        }
    }])

db.shipping.insertMany(
  [
     { custId: 456, purchaseDate: ISODate("2020-12-31") },
     { custId: 457, purchaseDate: ISODate("2021-02-28") },
     { custId: 458, purchaseDate: ISODate("2021-02-26") }
  ]
)

db.shipping.aggregate(
   [
      {
         $project:
            {
               expectedDeliveryDate:
                  {
                     $dateAdd:
                        {
                           startDate: "$purchaseDate",
                           unit: "day",
                           amount: 3
                        }
                  }
            }
       },
       {
          $merge: "shipping"
       }
    ]
 )


db.shipping.aggregate(
   [
      {
         $project:
            {
               expectedDeliveryDate:
               {
                   $add: ["$purchaseDate", 1000 * 60 * 60 * 24]
               }
            }
       },
       {
          $merge: "shipping"
       }
    ]
 )

db.shipping.update(
   { custId: 456 },
   { $set: { deliveryDate: ISODate( "2021-01-10" ) } }
)
db.shipping.update(
  { custId: 457 },
  { $set: { deliveryDate:  ISODate( "2021-03-01" ) } }
)
db.shipping.update(
   { custId: 458 },
   { $set: { deliveryDate:  ISODate( "2021-03-02" ) } }
)


db.shipping.aggregate([
{$match: { $expr: { $gt:[ "$deliveryDate", { $add: ["$purchaseDate", 1000 * 60 * 60 * 24] } ]}} },
{
    $project: {
     _id:  0,
     custId: 1,
     purchased: {$dateToString: { format: "%Y-%m-%d", date: "$purchaseDate" }},
     deliveryDate: {$dateToString: { format: "%Y-%m-%d", date: "$deliveryDate" }}
    }
}
])

 $dateToString: { format: "%y-%m-%d" }

db.billing.aggregate(
    [
        {
            $project:
                {
                    _id: 0,
                    location: 1,
                    start:
                        {
                            $dateToString:
                                {
                                    format: "%Y-%m-%d %H:%M",
                                    date: "$login"
                                }
                        },
                    days:
                        {
                            $dateToString:
                                {
                                    format: "%Y-%m-%d %H:%M",
                                    date: { $add: ["$login", 1000 * 60 * 60 * 24] }
                                }
                        },
                    hours:
                        {
                            $dateToString:
                                {
                                    format: "%Y-%m-%d %H:%M",
                                    date: { $add: ["$login", 1000 * 60 * 60 ] }
                                }
                        },
                    startTZInfo:
                        {
                            $dateToString:
                                {
                                    format: "%Y-%m-%d %H:%M",
                                    date: "$login",
                                    timezone: "$location"
                                }
                        },
                    daysTZInfo:
                        {
                            $dateToString:
                                {
                                    format: "%Y-%m-%d %H:%M",
                                    date:
                                        {
                                            $add: ["$login", 1000 * 60 * 60 * 24]
                                        },
                                    timezone: "$location"
                                }
                        },
                    hoursTZInfo:
                        {
                            $dateToString:
                                {
                                    format: "%Y-%m-%d %H:%M",
                                    date: new Date(),
                                    timezone: "+05:30"
                                }
                        },
                }
        }
    ]
).pretty()

/*
$dateAdd:
    {
        startDate: "$login",
        unit: "day",
        amount: 1,
        timezone: "$location"
    }
    */

db.sales.insertOne({
  "_id" : 5,
  "item" : "abc",
  "price" : 10,
  "quantity" : 2,
  "date" : ISODate("2021-10-07T12:57:39.736Z")
})


db.sales.find({})

db.sales.aggregate(
   [
     {
       $project: {
          yearMonthDayUTC: { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
          timewithOffset530: { $dateToString: { format: "%H:%M:%S:%L%z", date: "$date", timezone: "+05:30" } },
          minutesOffsetKolkataIST: { $dateToString: { format: "%Z", date: "$date", timezone: "Asia/Kolkata" } }

       }
     }
   ]
)

         
          minutesOffset430: { $dateToString: { format: "%Z", date: "$date", timezone: "+04:30" } }
          timewithOffsetNY: { $dateToString: { format: "%H:%M:%S:%L%z", date: "$date", timezone: "America/New_York"} },

dateToString
dayOfMonth
incrementing-a-day-to-a-date-in-mongodb
merge

Seconds to Hours Conversion
How to Get the Current Date in JavaScript
Compare Two Dates in JavaScript
JavaScript: Get Number of Days Between Dates
Moment.js: A Better Date Library for JavaScript
Working with Moment.js Date Libraries

Leave a Reply

Your email address will not be published. Required fields are marked *