How to get year from the date in mongodb?

Member

by deron , in category: PHP Databases , 2 years ago

How to get year from the date in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by jerad , a year 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.

by giovanny.lueilwitz , 9 months ago

@deron 

In MongoDB, you can extract the year from a date using the $year aggregation operator. Here's an example:

1
2
3
4
5
6
7
db.collection.aggregate([
  {
    $project: {
      year: { $year: "$dateField" }
    }
  }
])


In the above example, replace collection with the name of your MongoDB collection, and dateField with the name of the date field from which you want to extract the year. The output will contain a new field called year that will hold the extracted year value.


For example, if you have a collection called employees with a field called hiringDate containing dates, you can write the following query to extract the year:

1
2
3
4
5
6
7
db.employees.aggregate([
  {
    $project: {
      year: { $year: "$hiringDate" }
    }
  }
])


This will return a document for each employee with an additional field called year containing the year from their hiringDate.