Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have documents with the following structure

{
    "_id":{"$oid":"..."},
    "work_type": "ASSIGNMENT",
    
    "materials": [
        {
        "driveFile": {
            "driveFile": {
                "id": "...",
                "title": "filename",
                "alternateLink": "https://drive.google.com/...",
                "thumbnailUrl": "https://drive.google.com/..."
            },
            "shareMode": "STUDENT_COPY"
        }
        },
        {
        "youtubeVideo": {
            "id": "tfdbq",
            "alternateLink": "https://www.youtube.com/watch?v=..."
            }
        }
    ]
}

And I want to convert the objects in the array to JSON strings so that I can import the materials field as a repeated string column in SQL

Resulting in:

{
    "_id":{"$oid":"..."},
    "work_type": "ASSIGNMENT",
    "materials": [
        "{"driveFile":{"driveFile":{"id":"...","title":"filename","alternateLink":"https://drive.google.com/...","thumbnailUrl":"https://drive.google.com/..."},"shareMode":"COPY"}}",
        "{"youtubeVideo":{"id":"tfdbq","alternateLink":"https://www.youtube.com/watch?v=..."}}""
    ]
}
question from:https://stackoverflow.com/questions/65922820/how-do-i-convert-an-array-of-objects-subdocuments-to-an-array-of-strings-in-a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

I am not sure is there any easy option do this, you can try $function operator starting from MongoDB v4.4, indirectly it is JavaScript code,

  • using aggregate()
  {
    $set: {
      materials: {
        $function: {
          body: function(materials) { 
            let m = []; 
            for (let i = 0; i < materials.length; i++) 
              m.push(JSON.stringify(materials[i])); 
            return m; 
          },
          args: ["$materials"],
          lang: "js"
        }
      }
    }
  }

Playground

Playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...