Is there a way to sort data by year and month in mongodb?

I'm trying to filter data by year in MongoDB based on a specific year and month. For example, if I pass in the year 2022, I only want to see data from that year. However, when I try using the $gte and $lte tags, it returns empty results. Can someone guide me on how to properly filter by a specific year and month, like for instance, year 2023 and month 11? Here is an example of the 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
  }

Answer №1

If you need to filter specific years and months that are not necessarily consecutive in a more flexible way, try this approach:

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

Test it out on the example playground

Answer №2

If you're looking to filter by the createdaAt field, assuming it's a valid date, here's how you can do it for a specific year:

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

To filter by a specific month, use:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The JavaScript program for the shopping list is experiencing issues with the formatting of list items

I have been working on developing a shopping list program using JavaScript. The program includes an input box and an "add item" button, which adds the text entered in the input field to an unordered list as a list item. Each list item also contains an imag ...

Issue: Encountered an error when attempting to use the multer module

Hello experts, I am venturing into backend technology for the first time. As part of my project, I am trying to upload files and text to my database using nodejs and mongoDB. However, I keep encountering an error message that is impeding my progress. I wou ...

calculating the size of an array in node.js

I received a form object from my AngularJS to Node.js and this is how it looks in the console: For two files, filenames : [object Object],[object Object] # filenames object for two files length: 2 # used object.length For one file, filenames : [object ...

Developing a production build of a React app on a high-end machine is taking an unexpectedly

Our team is facing challenges with the performance of our production build, as it is taking approximately 20 minutes to complete. We initially suspected that the issue might be related to our local machine's capabilities, so we decided to run the buil ...

Guide to dynamically generating Angular watchers within a loop

I'm looking to dynamically create angular watches on one or more model attributes. I attempted the following approach: var fields = ['foo', 'bar']; for (var i=0, n=fields.length; i<n; i++) { $scope.$watch('vm.model.&ap ...

Tips on integrating Codrops tutorial codes into a SilverStripe website project

Exploring the vast array of tutorials and code examples on the Codrops site has been an enlightening experience. Codrops Website I'm eager to incorporate some of these resources into my SilverStripe projects as well. SilverStripe CMS After learning h ...

Show all column data when a row or checkbox is selected in a Material-UI datatable

I am currently working with a MUI datatable where the properties are set as below: data={serialsList || []} columns={columns} options={{ ...muiDataTableCommonOptions(), download: false, expa ...

Learn how to store the outcomes of an HTTP operation within array.map() in JavaScript

Having read numerous articles, I am a complete beginner when it comes to async programming and struggling to grasp its concepts. My goal is to map a filtered array of objects and return the result of a function (an amount) to set as the value of pmtdue. De ...

Struggling with retrieving empty parameters, queries, and body from an Axios API call for the past three days. It's a learning experience as I am new to the MERN stack

There seems to be an issue where only empty JSON like {} is coming as output. I am looking for a way to access the parameters sent from the routes in this scenario. On the Frontend: let api = axios.create({ baseURL: "http://localhost:5000/validateSignI ...

Tips for modifying JSON property names during the parsing process

As outlined in the JSON.parse documentation, a reviver function can be utilized to modify the value of each property within the JSON data. Here is an example: JSON.parse('{"FirstNum": 1, "SecondNum": 2, "ThirdNum": 3}', function(k, v) { return ...

Silent response upon click event listener

I'm having an issue with a navbar item not calling the reverseService function on click as expected. Although my IDE is indicating that the reverseService function is never used, VueJS dev tool doesn't show any problems. However, manually changi ...

In my Node.js project, I am creating a condensed link by extracting an existing URL and saving it to my MongoDB database

Upon generating the short URL, I encounter an error when attempting to open it in my browser for redirection to the original URL. This browser error is displayed. Below is my code snippet:- This snippet is from my urlController.js file // const shortid = ...

dojo.xhrGet evaluating script tags

I have a piece of code that is similar to the following: var targetElem = dojo.byId('xyz'); var xhrArgs = { url: 'Welcome.do?call=JS', preventCache: true, load: function(data){ targetElem.innerHTML = data; dojo.parser.par ...

The Cordova advanced HTTP POST request functionality is not functioning as expected

I'm currently in the process of connecting my backend to a cordova application, and at this early stage of development, I'm attempting to test it in the browser. Unfortunately, I'm facing an issue with the post request not working, as well a ...

CSRF Error: Unauthorized Access Detected in Express and NodeJS

I've been attempting to create CSRF tokens in my Express application. Despite looking at similar questions, I haven't found a solution. Below is the code snippet from my app.js file: var app = express(); var connect = require('connect' ...

Validating properties of a class using Typescript's Class-Validator

I tried using the class-validator decorator library for validation processes on my sample project. However, it doesn't seem to be working as expected. The sample project aims to create projects based on user inputs, and I'm attempting to validate ...

How to Send Session Variables from Node.js to a SQL Server Function Call

Within a MS Teams BOT, I have successfully implemented dialog code that prompts users with a series of questions and then formats their responses within a session. session.send(`Details: <br/>Question1: ${session.dialogData.Question1} <br/>Q ...

Hover over a ListItem

Looking for advice on how to incorporate a Mouseover feature into a Material UI ListItem from the following link: http://www.material-ui.com/#/components/list. As the "SecondaryText" is limited to 2 lines, I am exploring options to display additional data ...

Tips on showing binary information as images using extjs 4

As the proud owner of a valid .JPEG image's binary data, I am on a quest to convert this information into an actual viewable image using Python. Seeking advice on how to successfully transform this binary code into a visually appealing .JPEG format w ...

Store the advertisement click into the database utilizing PHP, subsequently access the provided hyperlink

I am developing a custom WordPress widget that displays advertisements. I want to track clicks on these ads and store the data in a database. The database table for click tracking is already set up, and I have a function called f1_add_advert_click($advert ...