首页 > 解决方案 > Mongodb C# 驱动程序更新所有子数组元素

问题描述

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

按照链接,现在可以执行以下操作:

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

例如,这个请求将在我的情况下完成这项工作:

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

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

有人可以给我一个 C# 示例。

标签: c#mongodb

解决方案


你可以像这样实现它:

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

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

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


推荐阅读