How to use Timestamp Range In MongoDB
Let’s see How to query documents in the users
collection created on March 20, 2024, using MongoDB’s date range query operators $gte
(greater than or equal to) and $lte
(less than or equal to) with specific timestamps for the start and end of the day.
// Construct timestamp range for March 20, 2024
const startTimestamp = new Date('2024-03-20T00:00:00Z');
const endTimestamp = new Date('2024-03-20T23:59:59Z');
// Query documents created on March 20, 2024
db.users.find({
createdAt: {
$gte: startTimestamp,
$lte: endTimestamp
}
});
Output:
Explanation: This output is a result of querying the users
collection for documents created on March 20, 2024. The query filters the createdAt
field to be within the range of March 20, 2024, from 00:00:00 to 23:59:59 UTC. The output includes two documents representing users created on that date: Bob and Charlie. Each document contains fields such as _id
(a unique identifier), name
, email
, and createdAt
(the date and time the user was created).
How to Query MongoDB ObjectId by Date?
MongoDB ObjectId is an important element in document identification, but can it help us with date–based queries? Understanding the ObjectId’s structure and its potential for querying by date opens up new possibilities for data retrieval and analysis.
In this article, We will learn about how to perform query MongoDB ObjectId by date by understanding various approaches along with practical examples and so on.