本文介绍了使用c#驱动程序在MongoDB中使用此对象的另一个属性更新嵌套集合中的对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更新嵌套集合中的属性.所有示例都描述了有关设置具体值的内容,而不是有关其他字段中的值的说明.

I need to update property in nested collection. All examples describes about setting concrete value, but not about value from another field.

MongoDB版本:4.2

MongoDB version: 4.2

C#驱动程序版本:2.10.4

C# driver version: 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 ...
        },
      ] 
    }

我知道如何更新价格

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

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

But how i can update Variants.Price as Variants.OriginalPrice? Trying

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

但发生错误.

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

Upd 1: Variant contains other properties.

@Mickl的答案是解决方案,但是

@Mickl's answer is the solution, but

以最佳方式覆盖整个嵌套集合吗?

推荐答案

更新表达式的右侧需要是MongoDB聚合表达式 1 ,目前您正在使用常规的更新"句法.基于文档:

The right handside of your update expression needs to be a MongoDB aggregate expression1 and currently you're using the regular "update" syntax. Based on the docs:

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

The $map operator can be used to achieve what you want:

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

这篇关于使用c#驱动程序在MongoDB中使用此对象的另一个属性更新嵌套集合中的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 19:27