【问题标题】:How to update documents on the Mongo side? [duplicate]Mongo端如何更新文档? [复制]
【发布时间】:2016-07-08 01:36:04
【问题描述】:
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();

====

收到documents 后,我会处理我身边的每个文档。

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

如何在 mongo 端做Regex.Replace?还是只能在客户端发生?

下面的Replace 在 Mongo 端有效吗?

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

【问题讨论】:

标签: c# mongodb


【解决方案1】:

您可以使用 javascript 进行此操作,但请确保修复 filter 以使用 mongo shell

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

【讨论】:

  • 那么 C# 呢?
  • 我对 C# mongo 驱动不熟悉,只是想办法通过 C# 向 mongo 发送自然的javascript 命令
  • 请看我更新的问题。你认为它在 mongo 方面有效吗?
  • 再说一次,我不熟悉 C# mongo 驱动程序,所以无法回答。但我几乎可以肯定你应该save 而不是InsertOneAsync。因为 Insert 可能会在您想要编辑文档时插入其他文档
  • 这个正则表达式在 JS 中不能正常工作,它应该是 var pattern = /&lt;([^\s&lt;]*totalWork[^\s&lt;]*)&gt;[\s\S]*?&lt;/\1&gt;/i;
猜你喜欢
  • 1970-01-01
  • 2021-04-23
  • 2021-01-31
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-18
相关资源
最近更新 更多