37

How to create a date field with default value,the default value should be current timestamps whenever the insertion happened in the collection.

3
  • Are you using any driver? programming language?
    – Sede
    Apr 11, 2016 at 13:35
  • We are getting data from .Net services ..but that part is dont have access . Is there any way to create field with in Mongo setup itself. Apr 11, 2016 at 13:41
  • How are you inserting the document? are you using the mongodb-csharp driver or the shell?
    – Sede
    Apr 11, 2016 at 13:44

10 Answers 10

36

Thats pretty simple! When you're using Mongoose for example, you can pass functions as a default value. Mongoose then calls the function for every insertion.

So in your Schema you would do something like:

 {
   timestamp: { type: Date, default: Date.now},
   ...
 }

Remember to only pass the function object itself Date.now and not the value of the function call Date.now()as this will only set the Date once to the value of when your Schema got created.

This solution applies to Mongoose & Node.Js and I hope that is your usecase because you did not specify that more precisely.

1
  • 1
    Appreciate the note that, we need to pass function object and not invoke it right away! Nov 23, 2022 at 13:40
13

Use _id to get the timestamp.

For this particular purpose you don't really need to create an explicit field for saving timestamps. The object id i.e. "_id", that mongo creates by default can be used to serve the purpose thus, saving you an additional redundant space. I'm assuming that you are using node.js so you can do something like the following to get the time of particular document creation:

let ObjectId = require('mongodb').ObjectID
let docObjID = new ObjectId(<Your document _id>)
console.log(docObjID.getTimestamp())

And, if you are using something like mongoose, do it like this:

let mongoose = require('mongoose')
let docObjID = mongoose.Types.ObjectId(<Your document _id>)
console.log(docObjID.getTimestamp())

Read more about "_id" here.

1
8

When Creating Document, timestamps is one of few configurable options which can be passed to the constructor or set directly.

const exampleSchema = new Schema({...}, { timestamps: true });

After that, mongoose assigns createdAt and updatedAt fields to your schema, the type assigned is Date.

7

You would simply do this while inserting... for current timestamp.

collection.insert({ "date": datetime.now() } 
2
  • Thanks thalaiva.. This query we can handle to run every insertion through query i agree that.Is there any way to handle this date time insertion through configure like RDBMS concept the below query @columnName datetime default CURRENT_TIMESTAMP Apr 11, 2016 at 13:47
  • 1
    @JagadeesanG: you would need mongoose if you are going with a schema... mongodb is as such schemaless. mongoosejs.com/docs/2.7.x/docs/schematypes.html
    – Thalaivar
    Apr 11, 2016 at 13:50
4

Let's consider the user schema in which we are using created date, we can use the mongoose schema and pass the default value as Date.now

 var UserSchema = new Schema({
       name: {type: String, trim: true},
       created: {type: Date, default: Date.now}
});

If we want to save timetamp instead of number then use Number isntead of number like that

var UserSchema = new Schema({
       name: {type: String, trim: true},
       created: {type: Number, default: Date.now}
});

Note:- When we use Date.now() in the default parameter then this will only set the Date once to the value of when your Schema got created, so you'll find the dates same as the that in the other document. It's better to use Date.now instead of Date.now().

3

I just wish to point out that in case you want the timestamp to be stored in the form of an integer instead of a date format, you can do this:

 {
   timestamp: { type: Number, default: Date.now},
   ...
 }
3

Here's a command that doesn't set a default, but it inserts an object with the current timestamp:

db.foo.insert({date: new ISODate()});

These have the same effect:

db.foo.insert({date: ISODate()});
db.foo.insert({date: new Date()});

Be aware that Date() without new would be different - it doesn't return an ISODate object, but a string.

Also, these use the client's time, not the server's time, which may be different (since the time setting is never 100% precise).

0

Thanks friends .. I found another way to get timestamp from _id field. objectid.gettimestamp() from this we can get it time stamp.

0

This is a little old, however I fount when using the Date.now() method, it doesn't get the current date and time, it gets stuck on the time that you started your node process running. Therefore all timestamps will be defaulted to the Date.now() of when you started your server. One way I worked around this was to do the following:

ExampleSchema.pre('save', function (next) {
    const instanceOfSchema = this;
    if(!instanceOfSchema.created_at){
      instanceOfSchema.created_at = Date.now();
    }
    instanceOfSchema.updated_at = Date.now();
    next();
})
0

createdAt: {type: Date, default:Date.now},

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.