Update the input type from string to data in MONGO DB format

Is there a way to efficiently convert the inspection_date field in my database from string to date for all objects, similar to the structure below?

{"name": "$1 STORE",
"address": "5573 ROSEMEAD BLVD",
"city": "TEMPLE CITY",
"zipcode": "91780",
"state": "California",
"violations": [{
    "inspection_date": "2015-09-29",
    "description": "points ... violation_status\n62754 1 ... OUT OF COMPLIANCE\n62755 1 ... OUT OF COMPLIANCE\n62756 2 ... OUT OF COMPLIANCE\n\n[3 rows x 5 columns]",
    "risk": "Risk 3 (Low)"
}, {
    "inspection_date": "2016-08-18",
    "description": "points ... violation_status\n338879 2 ... OUT OF COMPLIANCE\n\n[1 rows x 5 columns]",
    "risk": "Risk 3 (Low)"
}]
}

Any suggestions on how to automatically convert all occurrences of the inspection_date field without manual intervention?

Answer №1

According to the recommendations of @turivishal, it is necessary to utilize both the $map and $dateFromString operators.

db.collection.aggregate([
  {
    "$addFields": {
      "violations": {
        "$map": {
          "input": "$violations",
          "in": {
            "$mergeObjects": [
              "$$this",
              {
                "inspection_date": {
                  "$dateFromString": {
                    "dateString": "$$this.inspection_date",
                    "format": "%Y-%m-%d",
                    "onError": null,
                    "onNull": null
                  }
                }
              }
            ],
            
          },
          
        }
      }
    }
  },
  
])

Experience the MongoDB Playground Sample Execution here!

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

Decoding JSON data to retrieve arrays of arrays

I need help with deserializing an array of arrays containing Strings using ObjectMapper. The input data looks like this: [["key", "value"], ["Car", "1"], ["SUV", "1.1"]] My attempted method for deserialization is as follows: JavaType itemType = objectMap ...

The Ajax call failed to connect with the matching JSON file

<!DOCTYPE html> <html> <body> <p id="demo"></p> <script <script> function launch_program(){ var xml=new XMLHttpRequest(); var url="student.json"; xml.open("GET", url, true); xml.send(); xml.onreadystatechange=fun ...

Risks associated with storing configuration files in JSON/CPickle are related to security

In search of a secure and flexible solution for storing credentials in a config file for database connections and other private information within a Python module. This module is responsible for logging user activity in the system through different handler ...

What are some ways to optimize the efficiency of handling a sizable JSON object in React Native?

I am currently developing an application using React Native and have encountered significant slowdowns during transitions when loading more data. I am exploring alternative app structuring methods to prevent these performance issues, especially as the JSON ...

Converting objects into JSON format

I'm trying to transform an object that looks like this: { user[id]: 1, user[name]: 'Lorem', money: '15.00' } Into the following structure: { user: { id: 1, name: 'Lorem', }, money: ...

Is it the practice of the Signalr server to dispatch a consolidated response for all pending requests when polled using longpolling?

We have been receiving a series of pending requests for a signalr client, which are grouped together as an array in the response of a poll. Here's how it looks: {"C":"s-0,9E632", "M":[ 84 {"H":"MyHub","M":"SetSomething","A":[{"myProp1":"setting","myP ...

Dealing with JSON object as a string in API using Laravel with PHP

I have a Python API that generates a JSON object with data on staff behavior. The response looks like this: { "Text":{ "0":"Very unfriendly staff at reception: not responding to needs and giving wrong information.", "1":"The staff are polit ...

Trouble arises when attempting to remove an object using a combination of Node.JS, Mongoose, MongoDB, and

In my setup, I have two collections: one is called subcategories and the other is called categories. The categories collection includes a field known as subcategories which is an array containing the ids of the subcategories from the subcategories collecti ...

Utilize global variables in ng-apimock mocks without the need for double quotes

We integrated ng-apimock into our Angular project and successfully created mock definitions and wrote tests using protractor. Now we are looking to implement global variables in our mock definitions. Here is an example of a mock definition: { "expressi ...

Ways to extract an object from JSON into PHP

Can someone help me figure out how to extract an image link from this API ()? The API endpoint is https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&piprop=original&titles=Minecraft&pilicense=any. I've tri ...

iOS AFNetworking post request generates an error: Request failed due to a bad request (400)

When I use AFNetworking to make a post web service call, I consistently receive the following response: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" Below is my code snippet: NSURLSessionConfig ...

What is the best method for combining three tables in pandas that have varying numbers of columns?

My challenge started when I encountered a JSON file containing specific "device" details with various parameters for different devices. I managed to extract each device's JSON data as a separate row in a DataFrame, with each row consisting of 40-60 c ...

Building a JSON array within an array within an input in Rails 4

Currently, the content within my form is as follows: <%= f.input :document, collection: @documents, wrapper: false, label: false, input_html: {class: 'fleft mleft5'} %> This will result in a JSON array: [{ "document":"126" }] In My C ...

How can we prevent overflowing events in fullcalendar?

I am currently working on integrating the fullcalendar plugin with my JSON data, and so far it's been a smooth process. While I have successfully loaded my JSON data, I have noticed that on some days there are too many events being displayed at once. ...

Using the latitude and longitude data extracted from a MYSQL database using JSON in the Android platform, we can uniquely pinpoint and display markers on

I have retrieved a set of latitude and longitude values from a MYSQL DB in my Android app using JSON (obtained from PHP code). I am able to display these locations on a map successfully. However, I am struggling to figure out how to add markers to these lo ...

Asking for an API request in python that necessitates an oauth token

As I work on a program to send data to a specific URL and receive a response, I encountered an issue while using Python. The problem arose when trying to include a token in the request as required by Postman, resulting in a [401] response. The main obstac ...

The execute command within a function is malfunctioning in Python 3.5

Currently, I am working on a python program that aims to parse JSON files based on their tags using the Python `exec` function. However, I encountered an issue where the program fails when the `exec` statement is within a function. RUN 1: Exec in a functi ...

"Develop an API using NodeJs and Mongoose where every request is seamlessly directed to another collection

I am currently developing a Node.js API for an app that involves users, and I want each user to have their own MongoDB collection. Currently, everything is functioning properly. However, I notice that when I access collections dynamically, the process slo ...

Exploring the depths of Javascript objects using Typescript

If I have this specific dataset: data = { result: [ { id: '001', name: 'Caio B', address: { address: 'sau paulo', city: 'sao paulo', ...

Guide on retrieving data from a database and showcasing it on an HTML5 webpage using the combination of jqTouch and PhoneGap

I am currently working on developing an iPhone application for mobile health using a combination of HTML5, Javascript, jQTouch, and PhoneGap. This project is part of my school assignment aimed at gaining hands-on experience in building an iPhone app with t ...