I need to return each document creation date as a result of the find query. It's quite easy but I think I couldn't find the best appropriate and efficient way.
Think about 2 options.
Inserting documents with time stamp field.
Try to use the advantage of
ObjectId
field. I know thatcreated at
can be reached as;ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp()
but this returns inISODate
format. To be able to convertISODate
toDate
I can use Convert ISO Date to Date Format yyyy-mm-dd format in javascript
But I wonder, isn't there a way to use ObjectId time-stamp in a much more efficient way?
What I am trying to say can be seen in an example. Assume I have a database structure as;
[{_id: "56c70fe39114aeb633b7f19f" , name: "alex"},
{_id: "56cb04630000000000000000" , name: "felix"}]
first option is adding times-stamp field while inserting the documents. So the db becomes;
[
{_id: "56c70fe39114aeb633b7f19f" , name: "alex", timestamp: ""},
{_id: "56cb04630000000000000000" , name: "felix", timestamp: ""}
]
Query is simple as;
db.collection.find({}, {name: 1, timestamp: 1}).toArray({
//loop through each document and convert timestamp to date object
})
In the second option
db.collection.find({}).toArray({
//loop through each document and convert objectId to isoDate and and convert it to date object.
})
In any options, should I trace the the result and convert the time? What do you suggest?
Both way is not practical. I really wonder, is there a module that handles this situation? Or way to do?