使用 c# 驱动程序使用 MongoDB 中此对象的另一个 属性 更新嵌套集合中的对象 属性

Updating an object property in a nested collection with another property of this object in MongoDB with c# driver

我需要更新 嵌套 集合中的 属性。所有示例都描述了设置具体值,但没有描述来自另一个字段的值。

MongoDB版本:4.2

C#驱动版本:2.10.4

产品示例:

    {
     _id: "1",
     Title: "Some title",
     Price: 20,
     OriginalPrice: 10,
     ... other props ...
     Variants: 
      [
        {
           Price: 21,
           OriginalPrice: 11
           ... other props ...
        },
        {
           Price: 22,
           OriginalPrice: 13
           ... other props ...
        },
      ] 
    }

我知道怎么更新了Price

var pipeline = PipelineDefinition<Product, Product>.Create("{'$set': {'Price': '$OriginalPrice'}}");
productCollection.UpdateMany(FilterDefinition<Product>.Empty, Builders<Product>.Update.Pipeline(pipeline));

但是我如何才能将 Variants.Price 更新为 Variants.OriginalPrice?正在尝试

var pipeline = PipelineDefinition<Product, Product>.Create("{'$set': {'Price': '$OriginalPrice', 'Variants.$[].Price': '$Variants.$[].OriginalPrice'}}");
productCollection.UpdateMany(FilterDefinition<Product>.Empty, Builders<Product>.Update.Pipeline(pipeline));

但是出现错误。

更新 1:变体包含其他属性。

@Mickl 的 是解决方案,但是

覆盖整个嵌套集合是否是最佳方式?

更新表达式的右侧需要是 MongoDB 聚合表达式1 and currently you're using the regular "update" syntax. Based on the docs:

Specify the name of each field to add and set its value to an aggregation expression. For more information on expressions, see Expressions

可以使用$map运算符来实现你想要的:

var set = @"{
         $set:
            {
                Variants:
                {
                    $map:
                    {
                        input: '$Variants',
                            in: { $mergeObjects: [ '$$this', { Price: '$$this.OriginalPrice' } ] }
                    }
                }
            }
        }";

var pipeline = PipelineDefinition<Product, Product>.Create(set);

var res = productCollection.UpdateMany(FilterDefinition<Product>.Empty, Builders<Product>.Update.Pipeline(pipeline));