Home > Web Front-end > JS Tutorial > body text

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

DDD
Release: 2024-10-25 12:55:30
Original
806 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!