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

How to Query MongoDB Documents Based on Their Creation Date Using ObjectId?

Susan Sarandon
Release: 2024-10-25 12:02:30
Original
243 people have browsed it

How to Query MongoDB Documents Based on Their Creation Date Using ObjectId?

Querying MongoDB ObjectId by Date

ObjectIds in MongoDB embed the timestamp of their creation. This allows you to query documents based on the date the ObjectId was created.

For detailed implementation, refer to "Popping Timestamps into ObjectIds." Here's a brief overview in JavaScript:

<code class="javascript">function objectIdWithTimestamp(timestamp) {
    if (typeof(timestamp) == 'string') {
        timestamp = new Date(timestamp);
    }
    var hexSeconds = Math.floor(timestamp/1000).toString(16);
    var constructedObjectId = ObjectId(hexSeconds + "0000000000000000");
    return constructedObjectId
}

/* Find all documents created after midnight on May 25th, 1980 */
db.mycollection.find({ _id: { $gt: objectIdWithTimestamp('1980/05/25') } });</code>
Copy after login

The above is the detailed content of How to Query MongoDB Documents Based on Their Creation Date Using ObjectId?. 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
Latest Articles by Author
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!