0

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.

  1. Inserting documents with time stamp field.

  2. Try to use the advantage of ObjectId field. I know that created at can be reached as; ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp() but this returns in ISODate format. To be able to convert ISODate to Date 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?

Community
  • 1
  • 1
mmu36478
  • 1,295
  • 4
  • 19
  • 40

1 Answers1

0

If you need a conversion of JS Date object only in order to display that date somewhere, you can format ISODate object with help of $dateToString operator in aggregation framework

db.collection.aggregate(
   [
     {
       $project: {
          yearMonthDay: { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
          time: { $dateToString: { format: "%H:%M:%S:%L", date: "$date" } }
       }
     }
   ]
)

that will return

{ "_id" : 1, "yearMonthDay" : "2014-01-01", "time" : "08:15:39:736" }

So you need to have date field in documents

Oleks
  • 1,633
  • 1
  • 18
  • 22
  • Thank you for your answer, I want to display each document's creation date. I try `dateToString` with `_id` field but it said **can't convert from BSON type OID to Date** So you suggest me to select the first option and add a new date field? – mmu36478 Jan 20 '17 at 08:00
  • @mmu36478 yes, you will need the date field if you want to do that job in one query – Oleks Jan 20 '17 at 09:12