How to Query MongoDB ObjectId by Date?
Last Updated :
26 Mar, 2024
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.
What is an ObjectId in MongoDB?
- ObjectId is generated by MongoDB drivers to uniquely identify each document.
- The timestamp part of ObjectId allows for indirect date-based queries.
- The machine identifier ensures uniqueness across different machines.
- The process identifier helps ensure uniqueness in case of multiple operations within the same second.
- ObjectId is represented as a 24-character hexadecimal string.
- It is stored in the _id field of each document by default.
- ObjectId values are not sequentially generated but are designed to be globally unique.
How to Query MongoDB ObjectId by Date?
Although ObjectId is primarily used as a unique identifier, it can be used indirectly for date-based queries. However, it's important to note that ObjectId does not store timezone information, so queries based on date will be in UTC. Below are some methods that help us to perform query MongoDB ObjectId by date as follows:
- Using Timestamp Range
- Using ObjectId's First Four Bytes
- Using Aggregate Framework
Let's set up an Environment:
db.users.insertMany([
{ name: "Alice", email: "[email protected]", createdAt: ISODate("2024-03-19T10:00:00Z") },
{ name: "Bob", email: "[email protected]", createdAt: ISODate("2024-03-20T08:30:00Z") },
{ name: "Charlie", email: "[email protected]", createdAt: ISODate("2024-03-20T14:45:00Z") },
{ name: "David", email: "[email protected]", createdAt: ISODate("2024-03-21T12:00:00Z") },
]);
Output:
data inserted1. Using Timestamp Range
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:
Using timestamp rangeExplanation: 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).
2. Using ObjectId's First Four Bytes
Suppose we have Given a MongoDB collection of users where each document contains an _id
field representing the ObjectId of the document, we need to construct an ObjectId corresponding to March 20, 2024. Using this ObjectId, we are required to query and retrieve documents created after and before March 20, 2024, from the collection.
// Construct ObjectId for March 20, 2024
const objectIdForDate = ObjectId(Math.floor(startTimestamp.getTime() / 1000).toString(16).padStart(24, '0'));
// Query documents created after March 20, 2024
db.users.find({
_id: { $gt: objectIdForDate }
});
// Query documents created before March 20, 2024
db.users.find({
_id: { $lt: objectIdForDate }
});
Output:
OutputExplanation: This output is a list of MongoDB documents from a collection called users
. Each document represents a user and includes fields like _id
(a unique identifier), name
, email
, and createdAt
(the date and time the user was created). Each user's information is stored as a separate document in the collection.
3. Using Aggregate Framework
Let's see How to use the MongoDB aggregation pipeline to filter documents in the users
collection based on their createdAt
field, selecting only those created within a specified date range?
db.users.aggregate([
{
$match: {
createdAt: {
$gte: startTimestamp,
$lte: endTimestamp
}
}
}
])
Output:
Using Aggregate FrameworkExplanation: This output includes documents from the users collection that have a createdAt timestamp falling within the specified range for March 20, 2024. Each document includes fields such as _id, name, email, and createdAt, providing details of the users created on March 20, 2024.
Conclusion
Overall, MongoDB ObjectId, primarily a unique identifier, can be indirectly used for date-based queries, offering a versatile approach to data retrieval. By leveraging the timestamp embedded within ObjectId, developers can perform date-based operations effectively. The methods discussed - using timestamp range, ObjectId's first four bytes, and the aggregate framework - provide valuable insights into how MongoDB's flexibility extends to date-related queries, enhancing the database's utility in various applications.
Similar Reads
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. SQL is widely supported across various database systems like MySQL, Oracl
8 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
ACID Properties in DBMS In the world of DBMS, transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliability. This is where the ACID prop
8 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
SQL Query Interview Questions SQL or Structured Query Language, is the standard language for managing and manipulating relational databases such as MySQL, Oracle, and PostgreSQL. It serves as a powerful tool for efficiently handling data whether retrieving specific data points, performing complex analysis, or modifying database
15+ min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read