MongoDB 4.0 und neuer
Verwenden Sie $toDate
db.session_log.aggregate([
{ "$group": {
"_id": {
"$dateToString": {
"format": "%Y-%m-%d",
"date": {
"$toDate": {
"$multiply": [1000, "$LASTLOGIN"]
}
}
}
},
"count": { "$sum": 1 }
} }
])
oder $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 und <4.0:
db.session_log.aggregate([
{ "$group": {
"_id": {
"$dateToString": {
"format": "%Y-%m-%d",
"date": {
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
}
}
},
"count": { "$sum": 1 }
} }
])
Sie müssten den LASTLOGIN
umwandeln durch Multiplizieren des Werts mit 1000 auf einen Millisekunden-Zeitstempel
{ "$multiply": [1000, "$LASTLOGIN"] }
, dann in ein Datum umwandeln
"$add": [
new Date(0),
{ "$multiply": [1000, "$LASTLOGIN"] }
]
Dies kann im $projekt
Pipeline, indem Sie Ihre Zeit in Millisekunden zu einem Date(0)
von null Millisekunden addieren -Objekt und extrahieren Sie dann $year
, $month
, $dayOfMonth
Teile aus dem konvertierten Datum, die Sie dann in Ihrem $group
Pipeline, um die Dokumente nach Tag zu gruppieren.
Sie sollten daher Ihre Aggregationspipeline wie folgt ändern:
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 }
}
};
Ausführen der Aggregationspipeline:
db.session_log.aggregate([ project, group ])
würde die folgenden Ergebnisse liefern (basierend auf dem Beispieldokument):
{ "_id" : { "year" : 2014, "month" : 1, "day" : 3 }, "count" : 1 }
Eine Verbesserung wäre, obiges in einer einzelnen Pipeline als
auszuführenvar 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 }
}
};
Ausführen der Aggregationspipeline:
db.session_log.aggregate([ group ])