问题
I'm trying to set the time from a Date field to the start of the day
function getDate(date){ return new Date(date.getYear(), date.getMonth(),
date.getDate(), 0,0,0); }
...
{"$project" : {
"_id" : getDate("$dt"),
...
If I send
"$dt"
I getTypeError: date.getYear is not a function
as I'm passing a string,If remove the quotation marks, I get
Error: "$dt is not defined"
,- but if I set
"$dt"
as value for"_id"
I get a correct ISO Date.
So how do I pass the date object to the function?
回答1:
MongoDB's aggregation pipeline does not support JavaScript. To manipulate date values for results in the aggregation pipeline you need to use Date Aggregation Operators.
For example :
db.date.aggregate([
{ $project: {
_id: { $dateToString: { format: "%Y%m%d", date: "$dt" }}
}}
])
Assuming you have a document with a field called dt
with a date value of ISODate("2017-07-01T10:01:23.344Z")
, the result would look like:
{
"result": [
{
"_id": "20170701"
}
],
"ok": 1
}
Note: if you have multiple documents for the same day, this approach will create duplicate _id
values in your results. You may want to project to a different field name or perhaps use a $group stage instead of $project
if your intent is to combine values for the same day.
来源:https://stackoverflow.com/questions/44858270/how-can-i-manipulate-a-date-field-in-an-aggregation-pipeline