Converting isodate to numerical value Converting isodate to numerical value mongodb mongodb

Converting isodate to numerical value


Simply call the getTime() method, and you get the milliseconds since 1970/01/01

> var date_test = ISODate ("2013-07-26T22:35:40.373Z")> date_test.getTime()1374878140373

to convert milliseconds into date back, construct a new date object:

> new Date(1374878140373)ISODate("2013-07-26T22:35:40.373Z")


Starting Mongo 4.0, the $toLong aggregation operator can be applied on a Date to get a timestamp:

// { mydate: ISODate("2019-06-23T15:52:29.576Z")db.collection.aggregate({ $project: { timestamp: { $toLong: "$mydate" } } })// { timestamp: NumberLong("1561305149576") }

and vice versa with $toDate:

// { timestamp: NumberLong("1561305149576") }db.collection.aggregate({ $project: { mydate: { $toDate: "$timestamp" } } })// { mydate: ISODate("2019-06-23T15:52:29.576Z") }


If you are still having trouble define your model default as new Date() as this will give you long. See sample code below. Then you can always update the long values when you are in Java/Kotlin or any language | This will allow you to skip formatting dates in case you need to.

 var UserSchema = new Schema({username: {    type: String,    unique: true},email: {    type: String,    required: true,    unique: true},code: {    type: String,    default: ''},profileUrl: {    type: String,    default: ''},firstName: {    type: String,    default: ''},lastName: {    type: String,    default: ''},coordinates: {    type: String,    default: '0.0,0.0'},location: {    type: String,    default: ''},country: {    type: String,    default: 'Tanzania, United Republic of'},phoneNumber: {    type: String,    default: ''},deviceToken: {    type: String,    default: ''},firebaseUserId: {    type: String,    default: ''},created: {    type: Date,    default: new Date()},region: {    type: String,    default: 'Dar es salaam'},role: {    type: String,    default: 'normal'},lastActiveDate: {    type: Date,    default: new Date()}

});