Querying MongoDB ObjectId by Date
ObjectIds in MongoDB encode a timestamp representing the moment they were created. To utilize this feature for data retrieval, here's an explanation and example in JavaScript:
Querying with Embedded Dates
The following function generates an ObjectId containing a provided datetime:
<code class="javascript">function objectIdWithTimestamp(timestamp) { timestamp = new Date(timestamp); var hexSeconds = Math.floor(timestamp/1000).toString(16); return ObjectId(hexSeconds + "0000000000000000"); }</code>
To illustrate this usage, here's a query to find documents created after midnight on May 25th, 1980:
<code class="javascript">db.mycollection.find({ _id: { $gt: objectIdWithTimestamp('1980/05/25') } });</code>
This query effectively harnesses the embedded timestamp in the ObjectId to fetch relevant documents based on their creation date.
The above is the detailed content of How can I query MongoDB documents by their creation date using ObjectId\'s embedded timestamp?. For more information, please follow other related articles on the PHP Chinese website!