mongodbmongodb-querymongodb-update

Copy field of each element in an array of a sub-property to another field


I have a collection of documents in MongoDB that all look similar to this:

{
    "WorkspacePartTeamsite" : {
        "SiteContents" : [
            {
                "_id" : "00000000-0000-0000-0000-000000000002",
                "Name" : "PublicFiles",
            },
            {
                "_id" : "ad57fee3-e478-46a6-a8c1-499dcc98995f",
                "Name" : "Private",
            },
            ...
        ]
    }
}

The collection contains hundreds of documents like this.
I would like to update the "SiteContents"-Array and copy the property "Name" to another Property "SPOSegment".
A result could look like this:

{
    "WorkspacePartTeamsite" : {
        "SiteContents" : [
            {
                "_id" : "00000000-0000-0000-0000-000000000002",
                "Name" : "PublicFiles",
                "SPOSegment": "PublicFiles" 
            },
            {
                "_id" : "ad57fee3-e478-46a6-a8c1-499dcc98995f",
                "Name" : "Private",
                "SPOSegment": "Private" 
            },
            ...
        ]
    }
}

I tried already to write some queries, but they all do not work.
i.e:

db.collection.updateMany(
  {
    $set: {
      "WorkspacePartTeamsite.SiteContents": {
        $map: {
          input: "$WorkspacePartTeamsite.SiteContents",
          as: "item",
          in: {
            $mergeObjects: [
              "$$item",
              { SPOSegment: "$$item.Name" }
            ]
          }
        }
      }
    }
  }
)

Any proposal what I can do?


Solution

    1. You are missing the first argument which is used to filter the documents to be updated.

    2. As $map is aggregation operator, you should work with aggregation pipeline.

    db.collection.updateMany({},
    [
      {
        $set: {
          "WorkspacePartTeamsite.SiteContents": {
            $map: {
              input: "$WorkspacePartTeamsite.SiteContents",
              as: "item",
              in: {
                $mergeObjects: [
                  "$$item",
                  {
                    SPOSegment: "$$item.Name"
                  }
                ]
              }
            }
          }
        }
      }
    ])
    

    Demo @ Mongo Playground