Home > Software engineering >  MongoDB - Update All Map Values
MongoDB - Update All Map Values

Time:06-28

I have documents that are structured like this:

    // Document 1
    
        { 
          _id : "910",
          requests : {
            100 : {
              date : "10/06/2022 11:24:19"
              isProcessed : false
            },
            123 : {
              date : "10/06/2022 11:24:19"
              isProcessed : false
            },
          }
        }
    
    // Document 2

        { 
          _id : "743",
          requests : {
            999 : {
              date : "10/06/2022 11:24:19"
              isProcessed : false
            },
            152 : {
              date : "10/06/2022 11:24:19"
              isProcessed : false
            },
          }
        }

requests are saved as a map structure and the keys are different in each document. I want to change isProcessed to true in every value of every field in the requests map, and do it for all the documents. How can I do that?

CodePudding user response:

There are several issues with your documents/schema design.

  1. Using dynamic value as field names is generally considered as anti-pattern
  2. You are storing dates as strings. Consider storing them as proper date objects

Nevertheless, You can use $objectToArray to convert the requests object into an array of k-v tuples. Then use $mergeObjects to perform the update of isProcessed flag. Finally, use $arrayToObject to revert back to original structure.

db.collection.update({},
[
  {
    "$addFields": {
      "requests": {
        "$objectToArray": "$requests"
      }
    }
  },
  {
    "$addFields": {
      "requests": {
        "$map": {
          "input": "$requests",
          "as": "kv",
          "in": {
            k: "$$kv.k",
            v: {
              "$mergeObjects": [
                "$$kv.v",
                {
                  "isProcessed": true
                }
              ]
            }
          }
        }
      }
    }
  },
  {
    "$addFields": {
      "requests": {
        "$arrayToObject": "$requests"
      }
    }
  }
],
{
  multi: true
})

Here is the Mongo playground for your reference,

  • Related