【问题标题】:mongodb query updateMany : Updating fields in a list of embedded docs for all documents in a collectionmongodb 查询 updateMany :更新集合中所有文档的嵌入式文档列表中的字段
【发布时间】:2021-02-20 09:49:20
【问题描述】:

我有一个名为 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;
}

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

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

collection.updateMany(

 {},

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

 );

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

当我运行上述查询时,我收到以下错误:

未捕获的承诺拒绝:多个写入错误:[{写入错误: [{无法在元素中创建字段“dailyCapRunningTotal” {restrictionTracker: [ { dailyCapRunningTotal: 30 }, { dailyCapRunningTotal: 50 } ]}}]}, {}]

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

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

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 您能否提供您数据库中的示例文档。
  • @AnshumanTripathy 你的问题解决了吗?
  • @wak786 这是存储集合中单个文档的 json 表示 { "storeNum": "71249", "publicHealthUnit": "222", "restrictionTracker": [ { "dailyCapRunningTotal": 30, "weeklyCapRUnningTotal": 15 }, { "dailyCapRunningTotal": 20, "weeklyCapRunningTotal": 10 } ] } 我要做的就是更改每个 Store doc 的每个嵌入式文档中的 dailyCapRunningTotal 字段的值
  • @charlycou 还没有

标签: mongodb mongodb-query spring-data-mongodb mongodb-atlas


【解决方案1】:

您可以查看the positional operator $[]。 您可以尝试使用此查询

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

【讨论】:

  • 位置运算符是否只更改嵌入文档列表中的第一个嵌入文档?我在 Store 集合中有一个如下所示的文档: { "storeNum": "71249", "publicHealthUnit": "222", "restrictionTracker": [ { "dailyCapRunningTotal": 30, "weeklyCapRunningTotal": 15 }, { "dailyCapRunningTotal": 20, "weeklyCapRUnningTotal": 10 } ] } 我想更改每个 Store doc 的每个嵌入式文档中每个 dailyCapRunningTotal 字段的值
  • 它将更改所有嵌入的文档。 mongoplayground.net/p/mL4fQIc_2uJ
【解决方案2】:

我认为@charlycou 的回答应该有效。我不知道为什么它不适合你。

使用一些 cmets 添加不同版本的查询。还添加到 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    相关资源
    最近更新 更多