MongoDB 4.0 y posteriores
Utilice $toDate
db.session_log.aggregate([
{ "$group": {
"_id": {
"$dateToString": {
"format": "%Y-%m-%d",
"date": {
"$toDate": {
"$multiply": [1000, "$LASTLOGIN"]
}
}
}
},
"count": { "$sum": 1 }
} }
])
o $convert
db.session_log.aggregate([
{ "$group": {
"_id": {
"$dateToString": {
"format": "%Y-%m-%d",
"date": {
"$convert": {
"input": {
"$multiply": [1000, "$LASTLOGIN"]
},
"to": "date"
}
}
}
},
"count": { "$sum": 1 }
} }
])
MongoDB>=3.0 y <4.0:
db.session_log.aggregate([
{ "$group": {
"_id": {
"$dateToString": {
"format": "%Y-%m-%d",
"date": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
}
},
"count": { "$sum": 1 }
} }
])
Debería convertir el LASTLOGIN
campo a una marca de tiempo de milisegundos multiplicando el valor por 1000
{ "$multiply": [1000, "$LASTLOGIN"] }
, luego convertir a una fecha
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
y esto se puede hacer en el $project
tubería agregando su tiempo de milisegundos a un Date(0)
de cero milisegundos objeto, luego extraiga $year
, $month
, $dayOfMonth
partes de la fecha convertida que luego puede usar en su $group
pipeline para agrupar los documentos por día.
Por lo tanto, debe cambiar su tubería de agregación a esto:
var project = {
"$project":{
"_id": 0,
"y": {
"$year": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
},
"m": {
"$month": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
},
"d": {
"$dayOfMonth": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
}
}
},
group = {
"$group": {
"_id": {
"year": "$y",
"month": "$m",
"day": "$d"
},
"count" : { "$sum" : 1 }
}
};
Ejecutando la canalización de agregación:
db.session_log.aggregate([ project, group ])
daría los siguientes resultados (basado en el documento de muestra):
{ "_id" : { "year" : 2014, "month" : 1, "day" : 3 }, "count" : 1 }
Una mejora sería ejecutar lo anterior en una sola canalización como
var group = {
"$group": {
"_id": {
"year": {
"$year": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
},
"mmonth": {
"$month": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
},
"day": {
"$dayOfMonth": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
}
},
"count" : { "$sum" : 1 }
}
};
Ejecutando la canalización de agregación:
db.session_log.aggregate([ group ])