PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, December 30, 2021

[FIXED] How to store TimeStamp? Is there automatic field for CreatedOn

 December 30, 2021     cakephp, mongodb     No comments   

Issue

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?


Solution

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 :-)



Answered By - Abhay PS
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing