我正在努力将下面的代码转换为具有聚合功能的 MongoDB 驱动程序 C# 的“UpdateMany”,任何人都可以帮助我吗?
db.collection.updateMany(
{ URL: { $regex: /helloWorldt/ } },
[{
$set: { URL: {
$replaceOne: { input: "$URL", find: "helloWorldt", replacement: "helloWorld" }
}}
}]
)
谢谢,
coll.UpdateMany(
"{ URL: { $regex: '/helloWorldt/' } }",
PipelineDefinition<BsonDocument, BsonDocument>.Create(
BsonDocument.Parse($@"
{{
$set:
{{
URL:
{{
$replaceOne: {{ input: ""$URL"", find: ""helloWorldt"", replacement: ""helloWorld"" }}
}}
}}
}}")));
您可以在 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);