mongodb query updateMany : 更新集合中所有文档的嵌入式文档列表中的字段

mongodb query updateMany : Updating fields in a list of embedded docs for all documents in a collection

我有这样一个名为 Store 的集合:

    @Document("Store")
    public class Store implements Persistable<String> {
        
        @Id
        private String storeNum;
        
        private String publicHealthUnit;

        private List<RestrictionTracker> restrictionTracker;
}

嵌入式文档限制跟踪器如下所示:

public class RestrictionTracker {

    private int dailyCapRunningTotal;

    private int weeklyCapRunningTotal;
}

我正在尝试创建一个计划触发器,将每个 RestrictionTracker 嵌入式文档中 dailyCapRunningTotal 字段的所有值设置为 0 Store 集合中的每个文档 - 从美国东部标准时间中午 12 点开始每 24 小时(我将在格林威治标准时间配置 cron 表达式)

我正在尝试使用以下查询:

collection.updateMany(

 {},

 { $set: {"restrictionTracker.dailyCapRunningTotal":0}}

 );

商店集合中有一个文档,其中有一个 RestrictionTracker 列表,其中有 2 个文档 - dailyCapRunningTotal 字段设置为 30 和 50

当我 运行 上面提到的查询时,我得到以下错误:

uncaught promise rejection: multiple write errors: [{write errors: [{Cannot create field 'dailyCapRunningTotal' in element {restrictionTracker: [ { dailyCapRunningTotal: 30 }, { dailyCapRunningTotal: 50 } ]}}]}, {}]

在我看来,它试图创建一个值为 0 的新字段而不是替换现有值

不确定语法有什么问题,因为我正在使用以下在线手册中提供的查询:https://www.mongodbtutorial.org/mongodb-crud/mongodb-updatemany/

如有任何帮助,我们将不胜感激。谢谢。

你可以去the positional operator $[]看看。 你可以尝试使用这个查询

collection.updateMany({},{ $set: {"restrictionTracker.$[].dailyCapRunningTotal":0}});

我认为@charlycou 的回答应该有效。我不知道为什么它对你不起作用。

添加带有一些评论的不同版本的查询。还将 link 添加到 mongo 游乐场。

db.collection.update(
{},/**filter criteria that matches all documents in collection*/
{
  $set: {
    "restrictionTracker.$[].dailyCapRunningTotal": 0/** `$[]` means all the elements of array will get updated*/
    
  }
},
{
  multi: true/** will update all the documents matching the filter criteria and not only the first document.*/
  
})

MongoPlayGorund