Search code examples
arraysmongodbunset

MongoDB - How to remove part of field with $unset


I have a database in MongoDB where there are entries with the following structure image

I am using a script in Python that I use to retrive information from this strucutre and then saves it to a csv.

The end goal is to remove ONLY SOME parts of the parameters structure. For instance, I want to keep parameters[0].values and parameters[1].values but not parameters[2:5].values

I am not experienced in this but the command I am using is the following

{"$unset":"exercises.parameters.values"] }

but this will remove all values from all the objects inside parameters. Since the variable has the same name amongst the objects I can't find a way to specify which ones I want.

I have also tried indexing like so

{"$unset":"exercises.parameters[2].values"] }

but that doesn't seem to work...

Help is much appreciated!


Solution

  • update

    db.collection.update({
      "_id": 1
    },
    {
      "$unset": {
        "exercises.$[].parameters.2.values": "",
        "exercises.$[].parameters.3.values": "",
        "exercises.$[].parameters.4.values": "",
        "exercises.$[].parameters.5.values": ""
      }
    },
    {
      "multi": true
    })
    

    mongoplayground


    aggregate

    db.collection.aggregate([
      {
        $set: {
          "exercises": {
            "$map": {
              "input": "$exercises",
              "as": "item",
              "in": {
                "$mergeObjects": [
                  "$$item",
                  {
                    parameters: {
                      $slice: [ "$$item.parameters", 2 ]
                    }
                  }
                ]
              }
            }
          }
        }
      }
    ])
    

    mongoplayground