Introduction to MongoDB $year Operator

MongoDB is a popular NoSQL database that supports rich query operations, including various operators. The $year operator is one of the operators used to manipulate date-time types and extract the year from a date-time field.

Syntax

The syntax of the $year operator is as follows:

{ $year: <dateExpression> }

Here, <dateExpression> is an expression that represents a date-time field.

Use Cases

The $year operator can be used in various query scenarios, such as aggregating data based on year or finding data within a certain time frame.

Example

Suppose there is a collection named users that contains the following documents:

{
  "_id": 1,
  "username": "alice",
  "registerDate": ISODate("2022-02-28T12:34:56Z")
}
{
  "_id": 2,
  "username": "bob",
  "registerDate": ISODate("2021-03-15T09:15:23Z")
}
{
  "_id": 3,
  "username": "charlie",
  "registerDate": ISODate("2020-12-01T18:27:09Z")
}

We can use the $year operator to extract the year from the registerDate field and return the information of users who registered in 2021, as shown below:

Sample Data

db.users.insertMany([
  { _id: 1, username: "alice", registerDate: ISODate("2022-02-28T12:34:56Z") },
  { _id: 2, username: "bob", registerDate: ISODate("2021-03-15T09:15:23Z") },
  { _id: 3, username: "charlie", registerDate: ISODate("2020-12-01T18:27:09Z") }
])

Sample Code

db.users.find({ $expr: { $eq: [{ $year: "$registerDate" }, 2021] } })

Running the above code returns the following result:

{ "_id" : 2, "username" : "bob", "registerDate" : ISODate("2021-03-15T09:15:23Z") }

This query result contains only the information of the user bob, as he is the user who registered in 2021.

Conclusion

The $year operator can conveniently extract the year from a date-time field and can be used in various query and aggregation scenarios.