Working With Date, Regex, And Arrays In MongoDB (GAURI GAWANDE)
Da
- Dates:
MongoDB uses the Date
type to store date and time values. Dates are stored in ISODate format, which includes both date and time.
syntax:
db.collection.insertOne({
name: "Gauri",
createdAt: new Date()
})
db.collection.find({
createdAt: { $gte: ISODate("2025-01-01"), $lt: ISODate("2025-12-31") }
})
Date operation:
$gte
, $lte
, $eq
– Compare dates$dateToString
– Format date$subtract
, $add
– Date arithmetic example:
Imagine an application where you want to record every time a user logs in, including the exact time of the login.- Inserting Login Records: When a user successfully logs in, you would insert a document into a login history collection. The document would include the user's ID and a login_time field, set to the current date and time using MongoDB's new Date() or ISODate() functionality.
- Regex:
syntax:
db.users.insertMany([
{ name: "Gauri Gawande" },
{ name: "Ashok Gawande" },
{ name: "Gauri Ashok" }])
db.users.find({
name: { $regex: "^Gauri", $options: "i" }
})
db.users.find({
name: { $regex: "Gawande$", $options: "i" }
})
example:
To find documents where a specific field contains a particular substring, use the basic regex
- Arrays:
syntax:
db.students.find({
subjects: "Math"
})
db.students.find({
subjects: { $all: ["Math", "English"] }
})
db.students.find({
subjects: { $size: 3 }
})
example:
E-commerce Product Tags: A product document might have an array field called tags to store keywords associated with the product, such as ["electronics", "laptop", "gaming"]. This allows for easy searching and filtering based on multiple categories
- future scope/use cases:
Dates:
- Time-series databases (e.g., IoT, stock prices)
- Analytics and reporting
- Scheduling and calendar apps
- Expiry and TTL (Time-To-Live) data management
Regex:
- Search engines and autocomplete
- Data validation (e.g., email, phone numbers)
- Log filtering and pattern matching
- Text mining and NLP preprocessing
Arrays:
- Nested data modeling (e.g., orders with items)
- Tagging systems (e.g., blog tags, product categories)
- Recommendation engines (e.g., user preferences)
- Real-time analytics on multi-value fields
Greate blog
ReplyDeleteNice π
ReplyDeleteNice blog
ReplyDeleteGreat
ReplyDeleteGreat π
ReplyDeleteVery well explained ππ
ReplyDeleteVery helpful
ReplyDeleteinformative and easy to understand
ReplyDeleteHelpful
ReplyDeleteNice blog π
ReplyDeleteInformative blog
ReplyDelete