Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to get specific month|year (not date)?
To get specific month or year values from MongoDB date fields, use the aggregation framework with $month and $year operators. These operators extract the numeric month (1-12) and year values from date fields.
Syntax
db.collection.aggregate([
{ $project: { field: 1, dateField: { $month: "$dateField" } } },
{ $match: { dateField: monthNumber } }
]);
Sample Data
db.specificMonthDemo.insertMany([
{ "StudentName": "Larry", "StudentDateOfBirth": new ISODate("1995-01-12") },
{ "StudentName": "Chris", "StudentDateOfBirth": new ISODate("1999-12-31") },
{ "StudentName": "David", "StudentDateOfBirth": new ISODate("2000-06-01") }
]);
{
"acknowledged": true,
"insertedIds": [ ObjectId("..."), ObjectId("..."), ObjectId("...") ]
}
Display all documents to verify the data ?
db.specificMonthDemo.find().pretty();
{
"_id": ObjectId("5cb9a9ca8f1d1b97daf71819"),
"StudentName": "Larry",
"StudentDateOfBirth": ISODate("1995-01-12T00:00:00Z")
}
{
"_id": ObjectId("5cb9a9db8f1d1b97daf7181a"),
"StudentName": "Chris",
"StudentDateOfBirth": ISODate("1999-12-31T00:00:00Z")
}
{
"_id": ObjectId("5cb9a9ee8f1d1b97daf7181b"),
"StudentName": "David",
"StudentDateOfBirth": ISODate("2000-06-01T00:00:00Z")
}
Method 1: Get Specific Month
Find students born in January (month 1) ?
db.specificMonthDemo.aggregate([
{ $project: {
StudentName: 1,
StudentDateOfBirth: { $month: "$StudentDateOfBirth" }
} },
{ $match: { StudentDateOfBirth: 1 } }
]);
{
"_id": ObjectId("5cb9a9ca8f1d1b97daf71819"),
"StudentName": "Larry",
"StudentDateOfBirth": 1
}
Method 2: Get Specific Year
Find students born in 1999 ?
db.specificMonthDemo.aggregate([
{ $project: {
StudentName: 1,
birthYear: { $year: "$StudentDateOfBirth" }
} },
{ $match: { birthYear: 1999 } }
]);
{
"_id": ObjectId("5cb9a9db8f1d1b97daf7181a"),
"StudentName": "Chris",
"birthYear": 1999
}
Method 3: Extract Both Month and Year
db.specificMonthDemo.aggregate([
{ $project: {
StudentName: 1,
birthMonth: { $month: "$StudentDateOfBirth" },
birthYear: { $year: "$StudentDateOfBirth" }
} }
]);
{
"_id": ObjectId("5cb9a9ca8f1d1b97daf71819"),
"StudentName": "Larry",
"birthMonth": 1,
"birthYear": 1995
}
{
"_id": ObjectId("5cb9a9db8f1d1b97daf7181a"),
"StudentName": "Chris",
"birthMonth": 12,
"birthYear": 1999
}
{
"_id": ObjectId("5cb9a9ee8f1d1b97daf7181b"),
"StudentName": "David",
"birthMonth": 6,
"birthYear": 2000
}
Conclusion
Use $month and $year operators within aggregation pipelines to extract specific date components. The $project stage extracts the values, and $match filters documents based on the extracted month or year numbers.
Advertisements
