skip to Main Content

I want to find the max and min values of the myUpdateTime field. It’s a timestamp but stored as a string.

"myUpdateTime": "2021-11-08T17:42:30.650Z",

2

Answers


  1. To find the maximum and minimum values of the "myUpdateTime" field, you can convert the timestamp strings to actual Date objects and then compare them.

          // Example data
        const data = [
          { myUpdateTime: "2021-11-08T17:42:30.650Z" },
          { myUpdateTime: "2021-11-09T15:21:10.850Z" },
          { myUpdateTime: "2021-11-06T12:35:20.250Z" },
        ];
    
        // Convert timestamps to Date objects and extract their time value
        const times = data.map((item) => new Date(item.myUpdateTime).getTime());
    
        // Find the minimum and maximum time value
        const minTime = Math.min(...times);
        const maxTime = Math.max(...times);
    
        // Convert the time values back to Date objects
        const minDate = new Date(minTime);
        const maxDate = new Date(maxTime);
    
        // Format the dates as strings
        const minDateString = minDate.toISOString();
        const maxDateString = maxDate.toISOString();
    
        console.log(`Min: ${minDateString}`);
        console.log(`Max: ${maxDateString}`);
    
    Login or Signup to reply.
  2. Would recommend that you should store the Timestamp value as Timestamp rather than string to improve the performance in case that every time you need to convert the field into Timestamp such for these scenarios:

    • Sort by timestamp
    • Filter timestamp by range/compare

    To get the min/max of myUpdateTime, you have to use $group operator to group by all documents. And perform the min and max value by converting the myUpdateTime into Timestamp value first.

    db.collection.aggregate([
      {
        $group: {
          _id: null,
          minUpdateTime: {
            $min: {
              $toDate: "$myUpdateTime"
            }
          },
          maxUpdateTime: {
            $max: {
              $toDate: "$myUpdateTime"
            }
          }
        }
      }
    ])
    

    Demo @ Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search