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?
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 -
If you are on mongo shell then new Date() would insert the current time.
db.mycollection.insert({ 'created_on' : new Date() })
And if you want to use raw PHP then -
$collection->save(array("created_on" => new MongoDate()));
Hope this helps :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With