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 convert the field value and create datetime day of month during projection?
To convert a field value and create datetime day of month during projection in MongoDB, use aggregate() with $unwind to flatten arrays and $dayOfMonth to extract the day from converted timestamps.
Syntax
db.collection.aggregate([
{ "$unwind": "$arrayField" },
{
"$project": {
"fieldName": 1,
"DayOfMonth": {
"$dayOfMonth": {
"$add": [new Date(0), { "$multiply": ["$timestampField", 1000] }]
}
}
}
}
]);
Sample Data
db.demo209.insertOne({
"_id": "101",
"details": [
{
"dat": 1528929908,
"Name": "Chris"
},
{
"dat": 1529082069,
"Name": "Carol"
}
],
"Age": 25,
"CountryName": "US"
});
{ "acknowledged": true, "insertedId": "101" }
Display all documents from the collection ?
db.demo209.find().pretty();
{
"_id": "101",
"details": [
{
"dat": 1528929908,
"Name": "Chris"
},
{
"dat": 1529082069,
"Name": "Carol"
}
],
"Age": 25,
"CountryName": "US"
}
Example
Convert the timestamp field and extract day of month during projection ?
db.demo209.aggregate([
{
"$unwind": "$details"
},
{
"$project": {
"Age": 1,
"CountryName": 1,
"Name": "$details.Name",
"DayOfMonth": {
"$dayOfMonth": {
"$add": [new Date(0), {
"$multiply": ["$details.dat", 1000]
}]
}
}
}
}
]);
{ "_id": "101", "Age": 25, "CountryName": "US", "Name": "Chris", "DayOfMonth": 13 }
{ "_id": "101", "Age": 25, "CountryName": "US", "Name": "Carol", "DayOfMonth": 15 }
How It Works
-
$unwindflattens the details array into separate documents -
$multiplyconverts Unix timestamp to milliseconds (multiply by 1000) -
$addadds milliseconds to Date(0) to create a proper Date object -
$dayOfMonthextracts the day number (1-31) from the resulting date
Conclusion
Use $dayOfMonth with timestamp conversion to extract day values during projection. The $multiply and $add operators convert Unix timestamps to MongoDB Date objects for date extraction operations.
Advertisements
