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

你可以像这样实现它:

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

假设你有一个名为History的对象:

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

SOME_OBJECT:

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

并且您希望将所有对象更新为NAME_OF_THE_ARRAY:

public async Task<bool> Update_NAME_OF_THE_ARRAY(string id)
{
var filter = Builders<History>.Filter.Eq("_id", ObjectId.Parse(id));
var update = Builders<History>.Update.Combine(
Builders<History>.Update.Set(x => x.NAME_OF_THE_ARRAY[-1].Name, "test")
Builders<History>.Update.Set(x => x.NAME_OF_THE_ARRAY[-1].Flag, false);
var result = await _historyCollection.UpdateOneAsync(filter, update);
return result.ModifiedCount > 0;
}

最新更新