Mysterious Transformation of ISO Date by Mongo

I updated the date format

"date" : "2016-02-22 13:52:23"

by executing the following code:

db.gmastats.find({date: {$not: {$type: 9}}}).forEach(function(doc) {doc.date = new Date(doc.date); db.gmastats.save(doc);})

Unfortunately, when I checked using Mongo, it returned:

 ISODate("-292275055-05-16T16:47:03.192Z")

How should I go about converting this to a valid date format?

Answer №1

The string representing the date is currently invalid, however a simple adjustment can make it valid. All that needs to be done is to insert a "T" between the "date" and "time" components, after which new Date() will function correctly.

 db.gmastats.find({ "date": { "$type": 2 } }).forEach(function(doc) {
    doc.date = new Date(doc.date.split(" ").join("T")); 
    db.gmastats.save(doc);
 })

It's crucial to note that simply searching for data that is not in BSON Date format is risky. It's imperative to focus exclusively on "string" data when working with strings.

Optimally, these actions should be performed using "Bulk" operations:

 var ops = [];
 db.gmastats.find({ "date": { "$type": 2 } }).forEach(function(doc) {
    ops.push({ "updateOne": { 
        "filter": { "_id": doc._id },
        "update": { "$set": { "date": new Date(doc.date.split(" ").join("T")) } }
    }});

    if ( ops.length == 1000 ) {
       db.gmastats.bulk_write(ops);
       ops = []
    }
 })

 if ( ops.length > 0 ) {
     db.gmastats.bulk_write(ops);
 }

This approach will significantly enhance speed and ensure exclusive updates solely to the "date" property, without interfering with concurrent write processes.

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

When removing a react component from the list, it results in the deletion of all other components within the same

Whenever I click a button, a new component is added to my list of components. Each component in the list has a delete button, which can remove the component from the list. https://i.sstatic.net/uH42y.png Each component, consisting of the text "New Item" ...

How can I use ngx-editor to insert an HTML block at the current cursor position by clicking a button?

I am currently using ngx-editor within Angular 7. My goal is to insert HTML at the cursor's position upon clicking on parameters from a list. The current view displays how the parameter is appended when clicked, as shown in the image attached https:// ...

Tips for navigating the material ui Expanded attribute within the Expansion Panel

After looking at the image provided through this link: https://i.stack.imgur.com/kvELU.png I was faced with the task of making the expansion panel, specifically when it is active, take up 100% of its current Div space. While setting height: 100% did achi ...

What is the best way to integrate Babel and React into my Express Application?

I must admit, I am a bit of a newbie when it comes to this, but I've been doing a lot of research trying to make this work with no luck so far. I enjoy working on my apps in Express and now I want to incorporate React for some of my reusable componen ...

Importing information from the Document Object Model in Vue.js, focusing on the action attribute of a form

Can Vue be used to create a binding where the data item in the Vue instance is initialized from the DOM? In my specific case, I want my Vue instance to receive the action attribute of a form element. For example, this is how my HTML would look like (the ...

Trouble with Angular toggle switch in replicated form groups

Currently, I have a form group that contains multiple form controls, including a toggle switch. This switch is responsible for toggling a boolean value in the model between true and false. Depending on this value, an *ngIf statement determines whether cert ...

What is the best way to sort out the <li> elements within a <ul> that has a specific id

<ul class="apple" id="A"> <li> <li> ..... ...... ...... </ul> <ul class="apple" id="C"> <li> <li> ...

React Image Slider not loading pictures

Can someone help me troubleshoot why my images are not displaying in the slider on my homepage? I have set up the slider using React Slideshow Image, but the images are not showing up for some reason. I am also wondering if anyone knows of any full-screen ...

How to display an element using an if statement in Next.js

I am attempting to incorporate a parameter into a nextJS component that will only display if a certain condition is met. At the moment, my code looks like this: return ( <div role="main" aria-label={this.props.title} classN ...

Tips for adding a value to a specific object in an array

I am currently utilizing Vue along with Vuetify's v-data-table to display some data. Everything is functioning as expected, but I also need to incorporate data from another API. Therefore, I am looking for a way to add items to an array of objects. ax ...

The custom button feature is unresponsive to the enter key

Within my Angular project, I have implemented a custom button component that serves as a submit-form-button across various sections of the application. The issue arises when attempting to submit any form on the website using the enter key while focused on ...

Unable to connect beyond the local network using Socket.io

server.js import { Server } from "socket.io"; const io = new Server(8000); io.on("connect", (socket) => { console.log(`connect ${socket.id}`); socket.on("ping", (cb) => { console.log("ping"); ...

Preventing Ng-repeat from refreshing after deleting using $http request

Once I remove an item from my list, the deleted object's data disappears, but the placeholder (empty row) lingers. (I tried using apply() with no luck) I have a standard CRUD interface displaying expenses. <table class="table table-striped"> ...

What is the reason behind the inability to save the outcome of a promise (or a sequence of promises) in a variable?

I have a query that I need help with: Could you possibly assist me in identifying the issue within this code snippet and explaining why it is not functioning properly? const fetch = require('node-fetch'); const fetchProm = (() => { retur ...

Unable to properly cancel a post request using abort functionality

In the process of building a Next.js app, I encountered an issue with calling a post request. I included a cancel button to halt the post request, and attempted to use abortController in conjunction with Axios (v1.4.0) to achieve this. Even though the &ap ...

Navigating through Leaflet to reference a .json file

Looking to integrate a .json vector layer into a Leaflet.js map, which can be seen on the GitHub page here, with the source code available here. Here's a condensed version of the file for reference (full version visible on the linked GitHub page). & ...

Attempting to dynamically change the text of a button in JavaScript without any user interaction

I have created a button function that displays a word's definition when clicked. However, I am now attempting to modify it so that the definitions are shown automatically every few seconds using "SetInterval" without requiring a click. I am unsure of ...

Steps for altering the index name in mongodb

This is the title of the coordinate index I utilized LongitudeLatitude_indexContents_1_prominent_-1 The -1 value is causing issues and has been automatically generated. I prefer to modify it to LongitudeLatitude_indexContents_1_prominent_min1 or somethi ...

I am interested in organizing elements within an array based on a specific field using pymongo

My MongoDB contains a table with the following structure: { "holdng_name":"MCT", "employes":[ {"name":"Koroglu", "number":4}, {"name":"Babek", "number":1}, {"name":"Uzun Hasan", "number":3}, {"name":"Fatali Xan", "number":2} ] } ...

Displaying Angular table rows with missing values (Error: Cannot access property 'length' of undefined)

In the view, I have a table displaying nested data using ng-repeat. I want to show only rows with empty cells (<textarea>) when a link is clicked to apply a filter. The text of the link should change to 'Show all data' so that clicking it a ...