如何存储TimeStamp?是否有CreatedOn的自动字段

Sad*_*san 5 cakephp mongodb

我是mongoDB的新手.我有以下代码创建集合和文档但没有时间戳字段.有没有办法created_on自动插入文档.

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" }
Run Code Online (Sandbox Code Playgroud)

我真正想要的是使用Cake PHP为我的文档分配默认的"created_on".那你怎么做的?

Abh*_* PS 14

除了"_id"字段外,Mongodb不会自动插入任何内容.您可以从"_id"字段获取插入时间,如下所示 -

ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp()

结果看起来像这样 -

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

如果你想自己插入created_on字段,那么 -

  1. 如果你在mongo shell上,那么新的Date()会插入当前时间.

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

  2. 如果你想使用原始PHP然后 -

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

希望这可以帮助 :-)