Để chuyển đổi giá trị số (timestamp Unix) thành ngày tháng trong projection, sử dụng aggregate() với $dayOfMonth. Tạo collection:
> db.demo209.insertOne({
"_id" : "101",
"details" : [
{ "dat" : 1528929908, "Name" : "Chris" },
{ "dat" : 1529082069, "Name" : "Carol" }
],
"Age" : 25,
"CountryName" : "US"
});
{ "acknowledged" : true, "insertedId" : "101" }
Hiển thị tài liệu:
> db.demo209.find().pretty();
Kết quả - dat là timestamp Unix (giây):
Aggregation chuyển timestamp sang ngày trong tháng:
> db.demo209.aggregate([ { "$unwind": "$details" }, { "$project": { "Age": 1, "CountryName": 1, "Name": "$details.Name", "DayOfMonth": { "$dayOfMonth": { "$add": [new Date(0), { "$multiply": ["$details.dat", 1000] }] } } }} ])Kết quả - DayOfMonth: 13 và 15 (tháng 6/2018):
Giải thích: Timestamp Unix tính bằng giây, MongoDB Date cần milliseconds.
$multiply: ["$details.dat", 1000]chuyển giây sang ms,$add: [new Date(0), ...]tạo Date object,$dayOfMonthtrích xuất ngày.