skip to Main Content

I want to filter data by year in MongoDB. If I pass year 2022 then show only 2022 year data and when I pass 2023 show 2023 data only. I am not getting how to filter. I use $gte and $lte tag but it return empty. Also let me know who I will filter by specific year and month. Let say year 2023 and month 11.
Data –

{
    _id: new ObjectId("63ac23187dc7d"),
    details: 'hii there i am feeling great today',
    status: '1',
    createdAt: 2021-11-28T11:06:00.736Z
  },
  {
    _id: new ObjectId("63ac23b357dc96"),
    details: 'hi i am feeling good today',
    status: '1',
    createdAt: 2022-12-28T11:08:40.400Z,
  },
  {
    _id: new ObjectId("63b2b2afa0d8e"),
    details: 'Hello!! This is Ankit and feeling good',
    status: '1',
    createdAt: 2022-11-14T10:31:36.098Z
  },
  {
    _id: new ObjectId("63b2b2sswa0d91"),
    details: 'Felling bad a bit',
    status: '1',
    createdAt: 2023-01-02T10:32:27.149Z
  },
  {
    _id: new ObjectId("63b2b2a0d94"),
    details: 'Hmm, its ok ok',
    status: '1',
    createdAt: 2023-01-02T10:33:19.386Z
  }

2

Answers


  1. If you are looking after a generic approach to filter specific years and months which are not necessarily consecutive, one option is:

    db.collection.find({
      $expr: {
        $and: [
          {$eq: [{$year: "$createdAt"}, 2022]},
          {$eq: [{$month: "$createdAt"}, 11]}
        ]
      }
    })
    

    See how it works on the playground example

    Login or Signup to reply.
  2. Assuming createdaAt is what you want to filter by, and that it is a true date. For a single year you’d write a query like this:

    db.collection.find({
     createdAt: { $gte: new Date("2022-01-01"), $lt: new Date("2023-01-01") }
    })
    

    For a single month, it’s:

    db.collection.find({
     createdAt: { $gte: new Date("2022-11-01"), $lt: new Date("2022-12-01") }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search