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

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

mongo shell - How do I convert an array of objects / subdocuments to an array of strings in a MongoDB Aggregation pipeline?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...