Mongodb C#驱动程序更新所有子数组元素

时间:2019-12-10 15:41:32

标签: c# mongodb

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

通过this链接,现在可以执行以下操作:

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#示例吗?

2 个答案:

答案 0 :(得分:2)

您可以这样实现:

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

答案 1 :(得分:-1)

让我们假设您有一个名为Yes or No question. Do you like to eat bread? yes -> 4 people answered or %67 no -> 2 people answered or %33 的对象:

History

还有SOME_OBJECT:

public class History : MongoDocument
{
   // here you have some other properties, and you have a list of objects
   public Guid Guid { get; private set; }
   public List<SOME_OBJECT> NAME_OF_THE_ARRAY { get; set; }
}

您想将所有对象更新为NAME_OF_THE_ARRAY:

public class SOME_OBJECT
{
  // here you have other properties
  public bool Flag { get; set; }
  public string Name { get; set; }
}