使用聚合管道“$replaceOne”更新 MongoDB C# 驱动程序

问题描述 投票:0回答:2

我正在努力将下面的代码转换为具有聚合功能的 MongoDB 驱动程序 C# 的“UpdateMany”,任何人都可以帮助我吗?

db.collection.updateMany(
  { URL: { $regex: /helloWorldt/ } },
  [{
    $set: { URL: {
      $replaceOne: { input: "$URL", find: "helloWorldt", replacement: "helloWorld" }
    }}
  }]
)

谢谢,

c# mongodb asp.net-core mongodb-.net-driver
2个回答
0
投票
        coll.UpdateMany(
            "{ URL: { $regex: '/helloWorldt/' } }",
            PipelineDefinition<BsonDocument, BsonDocument>.Create(
                BsonDocument.Parse($@"
                {{
                    $set:
                    {{
                        URL:
                            {{
                                $replaceOne: {{ input: ""$URL"", find: ""helloWorldt"", replacement: ""helloWorld"" }}
                            }}
                    }}
                }}")));

0
投票

您可以在 C# 中使用

UpdateMany
和聚合管道 (
PipelineDefinition
) 来实现此目的。可以使用嵌套
BsonDocument
:

构建管道
var filter = Builders<CollectionName>.Filter.Regex("URL", new BsonRegularExpression("helloWorldt"));
var pipeline = PipelineDefinition<CollectionName, CollectionName>.Create(
    new BsonDocument{
        {
            "$set", new BsonDocument{
                {
                    "URL", new BsonDocument{
                        {
                            "$replaceOne", new BsonDocument{
                                { "input", "$URL" },
                                { "find", "helloWorldt" },
                                { "replacement", "helloWorld" }
                            }
                        }
                    }
                }
            }
        }
    });
var update = Builders<CollectionName>.Update.Pipeline(pipeline);

await _collection.UpdateManyAsync(filter, update);
© www.soinside.com 2019 - 2024. All rights reserved.