How to get year from the date in mongodb?

Member

by deron , in category: PHP Databases , 8 months ago

How to get year from the date in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 3 months ago

@deron 

To get the year from a date in MongoDB, you can use the $year operator. This operator extracts the year from a date and returns it as an integer.


Here's an example of how you can use the $year operator in a MongoDB query:

1
2
3
4
5
db.collection.find({
   "dateField": {
      "$year": 2020
   }
})


This query will find all documents in the collection where the value of the dateField is a date that occurred in the year 2020.


You can also use the $year operator as part of the projection stage of a query. For example:

1
2
3
4
5
db.collection.find({}, {
   "year": {
      "$year": "$dateField"
   }
})


This will return a new field called "year" in the documents returned by the query, which will contain the year extracted from the value of the "dateField" field.


Note that the $year operator only works with dates, not with strings or any other data type. Make sure that the field you are using with the $year operator is of the Date type.