0

I am trying to update a value in my entire DB for every meeting I have. Currently it looks like this:

{
    "Referent" : null
    "Participants" : [ 
        {
            "Email" : "mail@mail1.com",
            "Present" : true
        }, 
        {
            "Email" : "mail@mail2.com",
            "Present" : false
        }, 
        {
            "Email" : "mail@mail3.com",
            "Present" : true
        }
    ]
}

I want this to happen:

if(meeting.Referent == null) {
    foreach(var participant in meeting.Partipants) {
        if(participant.Present) {
            meeting.Referent = participant.Email;
        }
    }
}

Obviously the code above doesn't work for a MongoCollection, but I hope it makes sense. I want to set a meeting referent to a random (first or last) participant who is present at the meeting.

How would I do that using MongoCollection, so I can run it in my Mongo Shell?

MortenMoulder
  • 6,138
  • 11
  • 60
  • 116

1 Answers1

0

Oh nice, I never knew you could type Javascript into the Mongo Shell. This is what I ended up with:

var meetings = db.meetings.find({
        Referent: null
}).toArray();

meetings.forEach(function(meeting) {
    if(meeting.Participants.length > 0) {
        meeting.Participants.forEach(function(participant) {
            if(participant.Present) {
                meeting.Referent = participant.Email;
            }
        });
        if(meeting.Referent == null) {
            meeting.Referent = meeting.Participants[0].Email;
        }
        db.meetings.updateOne({
            "_id": meeting._id
        }, {
            $set: {"Referent": meeting.Referent }
        });
    }
});

Works perfectly :)

MortenMoulder
  • 6,138
  • 11
  • 60
  • 116