2016-03-21 83 views
1
const string Pattern = @"(?si)<([^\s<]*totalWork[^\s<]*)>.*?</\1>"; 
var filter = Builders<JobInfoRecord>.Filter.Regex(x => x.SerializedBackgroundJobInfo, 
              new BsonRegularExpression(Pattern, "i")); 

var documents = await records.Find(filter).ToListAsync(); 

====如何更新Mongo方面的文檔?

我得到documents後,我跟在我身邊的每個文檔工作。

const string EmptyTag = "<$1></$1>"; 
var updatedJobInfo = Regex.Replace(document.SerializedBackgroundJobInfo, Pattern, EmptyTag); 

我該怎麼做在蒙戈方Regex.Replace?或者只能在客戶端發生?

以下Replace作品在蒙戈方面?

using (var cursor = await jobInfoDocuments.FindAsync<JobInfoRecord>(filter)) 
{ 
     while (await cursor.MoveNextAsync()) 
     { 
      var batch = cursor.Current; 
      foreach (var document in batch) 
      { 
       var newInfo = Regex.Replace(document.SerializedBackgroundJobInfo, regex, EmptyTag); 

        // Applying several operations within the one request. 
        operationList.Add(new UpdateOneModel<JobInfoRecord>(Builders<JobInfoRecord>.Filter.Eq("_id", document.JobId), 
                     Builders<JobInfoRecord>.Update.Set("SerializedBackgroundJobInfo", newInfo))); 
       } 
+0

哎喲!顯然應該在發佈賞金之前將這個問題作爲重複來解決。請參閱[MongoDB:使用來自同一文檔的數據更新文檔](http://stackoverflow.com/a/3792958/2313887),這意味着「循環」,而不是接受答案中字段重命名的輕微重構。這裏唯一實際的事情是你已經得到的答案[如何提高Mongo更新操作的性能?](http://stackoverflow.com/a/36191579/5031275) –

+1

Regex.replace不支持MongoDB服務器端,所以如果你有特殊需求,它必須在客戶端完成。 – Saleem

回答

1

你可以用javascript做,但可以肯定的修復filter工作與蒙戈外殼

db.records.find(filter).forEach(function (doc) { 
 
    var pattern = /<([^\s<]*totalWork[^\s<]*)>[\s\S]*?</\1>/i; 
 
    var EmptyTag = "<$1></$1>"; 
 
    
 
    doc.SerializedBackgroundJobInfo = doc.SerializedBackgroundJobInfo.replace(pattern, EmptyTag); 
 
    
 
    db.records.save(doc); 
 
})

+0

那麼C#呢? – Anatoly

+0

我對C#mongo驅動程序並不熟悉,但只是找到一種方法,通過C#發送自然的'javascript'命令給mongo。 – TomG

+0

請查看我更新的問題。你認爲它在mongo方面有效嗎? – Anatoly