2016-09-29 52 views
0

我試圖更新我的整個數據庫中的每個會議的值。目前,它看起來像這樣:MongoCollection更新,其中的值等於

{ 
    "Referent" : null 
    "Participants" : [ 
     { 
      "Email" : "[email protected]", 
      "Present" : true 
     }, 
     { 
      "Email" : "[email protected]", 
      "Present" : false 
     }, 
     { 
      "Email" : "[email protected]", 
      "Present" : true 
     } 
    ] 
} 

我希望這種情況發生:

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

顯然上面的代碼不會對MongoCollection工作,但我希望這是有道理的。我想爲會議中出席的隨機(第一位或最後一位)參與者設定會議參考。

我該怎麼做,使用MongoCollection,所以我可以在我的Mongo Shell中運行它?

回答

0

很好,我從來不知道你可以在Mongo Shell中輸入Javascript。這是我結束了:

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 } 
     }); 
    } 
}); 

完美的作品:)