mongodb- How to display a year from a date in find method

时间:2015-11-12 11:33:10

标签: mongodb

Im trying to display the years of date properties in a mongodb collection.

I have collection of vehicles that contains objects with a date property: manufacturingDate - Date (ISODate).

To display only the years there is one way to this with aggregate:

db.vehicles.aggregate(
    [
        { $project: { year: { $year: "$manufacturingDate" } } }
    ]
)

But I am not allowed to use aggregate so i need a way to take the year out of the ISODate in another way.

I have tried many things like:

db.vehicles.find({}, { manufacturingDate: { $year: 1 } } )

or:

db.vehicles.find({}, { year: { function() { return this.manufacturingDate.getFullYear() } } } )

But these are all syntax errors. So i hope you have a correct way to do this without aggregate. I prefer the find method but any other method will be good.

Thanks.

1 个答案:

答案 0 :(得分:1)

Here are two ways to do it. Of course; it would be nicer if we could just execute getFullYear within a forEach applied to the find() but this is what works for me so far.

  1. I found this on [link]http://grokbase.com/t/gg/mongodb-user/133nvkd48q/how-to-format-output-datetime and tweaked the example. Obviously there is more here than you need bu I left the extra bits for clarity.

//first create a function to handle the execution of the getFullYear function on the ISODate field.

function parse_date(obj) {
year = obj['manufacturingDate'].getFullYear();
month = obj['manufacturingDate'].getMonth() + 1;
day = obj['manufacturingDate'].getUTCDate();
hour = obj['manufacturingDate'].getUTCHours();
minute = obj['manufacturingDate'].getUTCMinutes();
obj['manufacturingDate'] = year + '/' + month + '/' + day + ' ' + hour + 
':' + minute
//printjson(obj);
printjson(year);
}

//then execute your query and apply the parse_date function above within   
the forEach of the find method.
db.sample.find({},{manufacturingDate:1}).forEach(parse_date)
  1. You can also iterate over the resultset as a cursor and applying the getFullYear function against the ISODate field.

    //iterate over cursor var mdate = myDocument.manufacturingDate; print (mdate.getFullYear());