skip to Main Content

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?

2

Answers


    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

    Login or Signup to reply.
  1. db.collection.updateMany(
        { "WorkspacePartTeamsite.SiteContents": { $exists: true } },
        {
            $set: {
                "WorkspacePartTeamsite.SiteContents.$[elem].SPOSegment": "$[elem].Name"
            }
        },
        {
            arrayFilters: [ { "elem.Name": { $exists: true } } ]
        }
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search