Home  >  Article  >  Web Front-end  >  How to Query MongoDB Documents Based on Their Creation Date Using ObjectId?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-25 12:02:30244browse

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>

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!

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