Mongodb C#驱动程序更新所有子数组元素 [英] Mongodb C# driver update all subarray elements

查看:65
本文介绍了Mongodb C#驱动程序更新所有子数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更新文档并为子文档数组设置一个值. 使用文档使用$[]运算符.

I want to update a document and set a value to an array of subdocument. Using the documentation I have to use the $[] operator.

链接之后,现在可以执行以下操作:

Following this link it is now possible to do stuff like this :

db.coll.update({}, {$set: {"a.$[].b": 2}})
Input: {a: [{b: 0}, {b: 1}]}
Output: {a: [{b: 2}, {b: 2}]}

例如,此请求将完成我的工作:

For example this request will do the job in my case :

db.collection.update(
   { "History": { "$elemMatch": { "status": { "$ne": "PROCESSED" } } } }, 
   { "$set": { "History.$[].flag": false } },
   { "multi": true }
)

但是我找不到用驱动程序在C#中执行$[]运算符的方法. 而且驱动程序文档中不包含该信息.

But I do not find the way to do the $[] operator in C# with the driver. And the driver documentation does not contain the information.

有人可以给我提供C#示例吗?

Can someone please provide me a C# sample.

推荐答案

您可以这样实现:

            collection.UpdateMany(
                x => x.History.Any(h => h.status != "PROCESSED"),
                Builders<YourType>.Update.Set("History.$[].flag", false));

这是另一种强类型的解决方案:

here's an alternative strongly-typed solution:

using MongoDB.Entities;
using MongoDB.Entities.Core;
using System.Linq;

namespace StackOverflow
{
    public class Test : Entity
    {
        public Event[] History { get; set; }
    }

    public class Event
    {
        public bool flag { get; set; }
        public string status { get; set; }
    }

    public class Program
    {
        private static void Main(string[] args)
        {
            new DB("test", "localhost");

            (new[] {
                new Test { History = new[]{
                    new Event { flag = true, status = "PROCESSED" } } },

                new Test { History = new[]{
                    new Event { flag = true, status = "NOT-PROCESSED" },
                    new Event { flag = true, status = "NOT-PROCESSED" }
                }}
            }).Save();

            var field = Prop.PosAll<Test>(t => t.History[0].flag);

            DB.Update<Test>()
              .Match(t => t.History.Any(h => h.status != "PROCESSED"))
              .Modify(b => b.Set(field, false))
              .Execute();
        }
    }
}

这篇关于Mongodb C#驱动程序更新所有子数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆