Splitting up collection into many collections

Hello everyone! Basically I have a collection that looks like so:

I am wondering how I can make a function that creates a seperate collection for each “randomString” object as well as includes the time.

I want each “randomString” Object contents:

lastBeat:1624014043
hr:12577203
offline:false

to be copied over to it’s own collection file with the name of the actual object it just copied over ZxCEuUp34WYFzZq7CQdRQGjjxC2DY…

End result should be something like 12 different collections each containing something along the lines of:

lastBeat:1624014043
hr:12577203
offline:false
time:"11:02"

Hi @David_Berndtsson, I’ve not tested it (and bulk inserts would be more efficient), but you could try something like this:

exports = function(){
    let db = context.services.get("mongodb-atlas").db("MyDB");
    let originalCol = db.collection("Original");
    let newCol = db.collection("New");
    
    originalCol.find()
    .then (reults => {
        let oldDocs = results.toArray();
        oldDocs.forEeach (oldDoc => {
            for (const element in oldDoc.randomString) {
                let newDoc = element;
                newDoc.time = oldDoc.time;
                newCol.insertOne(newDoc);
            }
        });
    });
}

It didn’t quite work. It complained about then not being defined.

I am really interested on how to query the database, and run code with a set var = the randomString for each of the randomString

Hi @David_Berndtsson – I just tested this version and it works:

exports = function(){
    let db = context.services.get("mongodb-atlas").db("random");
    let originalCol = db.collection("original");
    let newCol = db.collection("new");
    return originalCol.find().toArray()
    .then (results => {
        results.forEach( oldDoc => {
          for (const element in oldDoc.randomString) {
              let newDoc = oldDoc.randomString[element];
              newDoc.time = oldDoc.time;
              newCol.insertOne(newDoc);
            }
        });
    });
};