Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store TimeStamp? Is there automatic field for CreatedOn

I am new to mongoDB. I have following code create collection and document But there is no timestamp field. Is there any way to insert created_on automatically in documents.

db.createCollection("countries"); //Created collection
db.countries.insert({"short_name":"AF","country_name":"Afganistan"});  //Created document
db.countries.find()
{ "_id" : ObjectId("53d1d5bcb8173a625961ff34"), "short_name" : "AF", "country_name" : "Afganistan" }

What I am really after is assigning a default "created_on" to my documents using Cake PHP. So how do you do that?

like image 349
Sadikhasan Avatar asked Jul 25 '14 04:07

Sadikhasan


1 Answers

Mongodb will not insert anything automatically except the '_id' field. You can get the time of insertion from '_id' field like this -

ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp()

The result would look something like this -

ISODate("2012-10-15T21:26:17Z")

If you want to insert created_on field yourself then -

  1. If you are on mongo shell then new Date() would insert the current time.

    db.mycollection.insert({ 'created_on' : new Date() })

  2. And if you want to use raw PHP then -

    $collection->save(array("created_on" => new MongoDate()));

Hope this helps :-)

like image 147
Abhay PS Avatar answered Oct 13 '22 13:10

Abhay PS