【问题标题】:Mongoose - update last element in array (update document with an aggregator)Mongoose - 更新数组中的最后一个元素(使用聚合器更新文档)
【发布时间】:2020-07-06 10:26:26
【问题描述】:

我的问题建立在这个基础上:Get only the last element of array mongoose。但是,我正在使用 Mongoose,并且还想更新数组最后一个元素中的一个字段,而不仅仅是检索它。

如何修改rounds 数组中的最后一个元素/对象,以将status: started 更改为status: terminated

要修改的文档

{
    "_id" : "8844d3f2d25f45df8105db1ab058d7d6",
    "rounds" : [ 
        { "status" : "offline" },
        { "status" : "paused" },
        { "status" : "started" }
    ],
    "updatedAt" : ISODate("2020-07-05T21:21:58.823Z")
}

似乎使用负索引会使这变得容易,允许修改 n-1 元素。我看到很多问题都提到了聚合,但没有一个修改基础数据。我想将聚合与更新文档结合起来。

是否可以将$set 与负索引一起使用?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    从 v4.2 开始,MongoDB 没有直接按索引更新数组元素的方法。

    但是从 v4.2 开始,您可以使用updates with aggregation pipeline,它允许您基于当前数组构造一个新数组并替换当前数组。

    您可以构造一个新数组,而不是修改最后一个元素,该数组由第一个顶部 n - 1 元素与一个新元素 { status: "terminated" } 组合而成。

    您可以通过使用$slice 获取顶部n - 1 元素并使用$concatArrays 与新元素组合来实现此目的

    这假定元素仅包含字段status 您要更新包含多个字段的数组元素的字段,您需要使用$mergeObjects 将更新的字段与当前元素合并

    Model.updateOne({ // or updateMany with your condition
      _id: "8844d3f2d25f45df8105db1ab058d7d6"
    }, [{
      $set: {
        rounds: {
          $concatArrays: [ // combine arrays
            {
              $slice: [ // get the top n - 1 elements
                "$rounds",
                { $subtract: [{ $size: "$rounds" }, 1] }
              ]
            },,
            [{ status: "terminated" }] // a new element to replace the last element
          ]
        }
      }
    }])
    

    【讨论】:

      猜你喜欢
      • 2015-12-22
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 2017-03-31
      • 2022-12-05
      • 2022-01-22
      相关资源
      最近更新 更多