Retrieve data from MongoDB that is within the past week in ISO string format

My goal is to retrieve data from MongoDB that is exactly a week old.

The specific field I am focusing on is -

{
 _id:821398723913,
 closed_at:"2020-06-10T01:43:59-04:00"
}

I am looking to fetch all objects where the 'closed_at' field falls within a week's time frame. Despite searching online, none of the suggested solutions seem to be effective.

Edit:

Here are some attempts I have made so far -

db.Orders.aggregate([{
            $project: {
                date: {
                    $dateFromString: {
                        dateString: '$date'
                    }
                }
            }
        }, {
            $match: {
                "closed_at": {
                    $lt: lastDayWeek,
                    $gt: firstDayWeek
                }
            }
        }]);

and

Orders.find({'closed_at':  {
                $gte: new Date((new Date().getTime() - (15 * 24 * 60 * 60 * 1000)))
            }, 'cancelled_at': null}).sort({_id: 1});

I require the data to be fetched from Monday to Monday and I have been attempting to use $isoWeek without success so far

Answer №1

Here is a solution you can try out:

db.Orders.aggregate([
  {
    "$addFields": {
      "closed_at_iso": {
        "$toDate": "$closed_at"
      }
    }
  },
  {
    $match: {
      "closed_at_iso": {
        $gte: new Date(new Date() - 7 * 24 * 60 * 60 * 1000)
      }
    }
  }
])

The challenge here lies in the fact that the date field is stored as a string, so we need to convert it to an ISODate format first before using the $match operator.


Edit:

If you want to retrieve data between last week's Monday and this Monday, you can use the following query:

var start = new Date(2020, 5, 1), // date of last Monday
    end = new Date(2020, 5, 8);   // date of this Monday

db.collection.aggregate([
  {
    "$addFields": {
      "closed_at_iso": {
        "$toDate": "$closed_at"
      }
    }
  },
  {
    $match: {
      "closed_at_iso": {
        $gte: start,
        $lte: end
      }
    }
  }
])

If you prefer a dynamic approach to get the dates for last Monday and this Monday, you can use the function below:

function getMonday(d) {
  d = new Date(d);
  var day = d.getDay(), diff = d.getDate() - day + (day == 0 ? -6 : 1);
  return new Date(d.setDate(diff));
}       

var start = getMonday(new Date().setDate(new Date().getDate() - 7))
var end = getMonday(new Date())

console.log(start)
console.log(end)

Answer №2

Successfully resolved the issue with the help of palash's solution

let oneWeekAgo = new Date(new Date().getTime() - 60 * 60 * 24 * 7 * 1000)
            , dayOfWeek = oneWeekAgo.getDay()
            , daysToMonday = oneWeekAgo.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1)
            , previousMonday = new Date(oneWeekAgo.setDate(daysToMonday))
            , previousSunday = new Date(oneWeekAgo.setDate(daysToMonday + 6));


        const orders = await Orders.aggregate([
            {
                '$addFields': {
                    'created_at_iso': {
                        '$toDate': '$created_at'
                    }
                }
            },
            {
                $match: {
                    'created_at_iso': {
                        $gte: previousMonday,
                        $lte: previousSunday
                    }
                }
            }
        ]);

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

Using Crawler4j, Jsoup, and JavaScript to retrieve modified attribute values

Currently, I am utilizing Crawler4j and Jsoup for web crawling and it's performing well with HTML text. However, some vital contents have default values hardcoded in CSS and then dynamically adjusted through JavaScript. For instance, there's a e ...

Trigger next animation after the completion of current animation using Jquery animate callback

Is there a simpler way to achieve this task? var index = 0; while (index < 5) { $(this).find(".ui-stars-star-on-large:eq(" + index + ")").animate({ width: w + 'px' }, 200, "swing"); index++; } ...

Creating a unique theme export from a custom UI library with Material-UI

Currently, I am in the process of developing a unique UI library at my workplace which utilizes Material-UI. This UI library features a custom theme where I have integrated custom company colors into the palette object. While these custom colors work perfe ...

Leveraging JQuery for activating an event with Bootstrap Scrollspy

I'm facing a challenge in capturing the Scrollspy event to execute a specific function. The Scrollspy feature is functioning correctly in terms of updating the active link on the navbar. However, I am struggling to capture the event for use in other p ...

Animating a dotted border path in SVG for a progress bar effect

I am attempting to create an animation for a dotted SVG circle that resembles a progress bar, where it fills itself over a duration of 3 seconds. However, I am facing difficulties in achieving this effect with the dotted border. The current code I have doe ...

A distinctive noise is heard when hovering over multiple instances of a div

I'm trying to implement a feature where a unique sound plays when hovering over a specific div element with a particular class (.trigger). However, I am encountering an issue where multiple instances of this div class result in the same sound being pl ...

The absence of HttpOnly Secure Cookies being transmitted

Here we go again, another inquiry regarding httpOnly Cookies. Seems like many others are facing the same predicament as me. Even though I receive the cookie from the server, it doesn't accompany other requests. I have mysite.example.com in angularj ...

How can I pass props from a custom _app.js file to the <Navbar> component in Next.js?

How do I go about passing props to a Navbar component that will be included under the Head component? Although I successfully passed props in the index.js page using getServerSideProps, it seems to not work properly in the _app.js file. import ".. ...

Removing Click event upon button click - Implementing Vue and Vuetify

In my project using Vuetify, I have implemented a dialog that opens when a button is clicked. The dialog can be closed after completing the required actions. However, in the production environment, the dialog cannot be reopened more than once due to the re ...

Is it possible to update the value of an element using JavaScript?

My goal is to manipulate the content of a specific element on a third-party web page using a JavaScript Add-on in order to display a clickable hyperlink. I have already identified the link that I want to interact with on the page, and I believe document.g ...

Issue: React child components cannot be objects (received: object with keys)

Hey everyone, I could really use some help figuring out what I'm doing wrong. Here is the error message I'm receiving: Error: Objects are not valid as a React child (found: object with keys {id, title, bodyText, icon}). If you meant to render a ...

Updating an array element in MongoDB by setting it to a value from another array

I need assistance with creating a new array called methods[].linkToRegistry[] based on the data from methods[].settings[].linkToRegistry. Essentially, I want to iterate through all the settings[] elements and extract the linkToRegistry data into a new arra ...

Every Dynamic Post automatically defaults to the initial object

I am currently developing an app that retrieves feeds from a Wordpress site and displays individual posts in a jQuery mobile list format. Here is the JavaScript code I am using: $(document).ready(function () { var url = 'http://howtodeployit.com/ ...

Can someone please explain how to include a custom icon on Select component in Mantine without using an image from Tabler Icons library?

Hey there, I'm new to using Mantine and I'm currently working on a Search Component. Instead of utilizing an image from the tabler icons like in the Mantine examples, my goal is to include a picture from my own assets. Here's what I've ...

What is the best way to integrate server-side Joi validation with redux-form for seamless functionality?

On my back-end express server, I have implemented Joi validation. The validation messages from the backend are stored in a redux errors state object. However, I am facing challenges in setting up this redux object state to display the messages correctly on ...

Obtain the parameter of a parent function that runs asynchronously

Here's the code snippet I'm working with: function modify( event, document ) { console.log( "document name", document ); //I need it to be 'file', not 'document'. documents.clients( document, function( clientOfDocument ...

Is it possible for me to transform this code into a useful helper function?

I am looking to optimize this conditional code by converting it into a helper function using a switch statement instead of multiple if statements. How can I achieve this in a separate file and then import it back into my component seamlessly? import { ...

Obtain the model value using Yii jQuery and then proceed to submit the form

Within the _form.php view, there is a presence of $model and a CActiveForm $form. I implemented JavaScript code to compare the value of $model->publication_date with the current date. If they are identical, the form will be submitted automatically. Othe ...

Is there a pure JavaScript solution to replace jQuery's .prev() function?

Looking for a JavaScript alternative to this jQuery code: $(".q-block-container").prev(".sub-block-container").css("border-bottom","none"); I am seeking a pure JavaScript solution that selects the previous sibling ONLY if it matches a specific selector ( ...

Is there a way to replicate input data from one website onto a totally separate platform?

I am currently working on a hotel website using the user-friendly WYSIWYG site builder, Wix (yes, I know, don't judge). Like all hotel websites, we need a form for customers to enter their details for reservations and other purposes. However, there&a ...