c# - 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();
}
}
}
推荐阅读
- memory - xarray.Dataset.to_array() 是否将数组加载到内存中,以及从 xarray 中采样小批量的效率如何?
- python - 如何在画布内使用 Tkinter 滚动条
- java - Java - 无法解析构造函数
- amazon-web-services - 何时在 AWS 中通过 API Gateway 使用 Application Load Balancer?
- java - EntityManagerFactory.close() 不关闭 hibernate.connection.datasource-property 设置的 HikariDataSource
- momentjs - MomentJS 没有返回正确的信息
- pyspark - 使用 expr 函数对相反方向的 2 列进行排序不起作用
- sql - 计算视图中某些行的总和?
- elasticsearch - Elasticsearch查询过滤器组合问题
- ios - 有没有办法为仅在情节提要上可见的 UI 设置属性?