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!