Home  >  Article  >  Web Front-end  >  How can I query MongoDB documents by their creation date using ObjectId\'s embedded timestamp?

How can I query MongoDB documents by their creation date using ObjectId\'s embedded timestamp?

DDD
DDDOriginal
2024-10-25 12:55:30807browse

How can I query MongoDB documents by their creation date using ObjectId's embedded timestamp?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn