更新最后一个数组元素的字段,使其等于另一个字段。

huangapple go评论65阅读模式
英文:

Update the field of the last array element to equal another field

问题

我需要更新所有文档,并将最后一个成员的"left_at"字段设置为等于"end_time"字段。根据上面的对象,预期更新后的版本应为:

{
  _id: ObjectId(""),
  end_time: Date(164),
  members: [ 
    { user_id: "1", left_at: Date(73) },
    { user_id: "2", left_at: Date(164) }
  ]
}

注意:

  • 假设每个会话文档都包含至少1个元素的"members"。
  • 更明确地说,我指的是"最后"的成员,即索引members[members.length-1]
英文:

I have a collection of "sessions" (over 731,000 documents) which are structured like this:

{
  _id: ObjectId(""),
  end_time: Date(164),
  members: [ 
    { user_id: "1", left_at: Date(73) },
    { user_id: "2", left_at: Date(0) }
 ]
}

I need to update all documents and set the last member's "left_at" field to equal the "end_time" field.

So based on the object above, the intended updated version should be:

{
  _id: ObjectId(""),
  end_time: Date(164),
  members: [ 
    { user_id: "1", left_at: Date(73) },
    { user_id: "2", left_at: Date(164) }
 ]
}

NOTE:

  • Assume that every session document has a members containing at least 1 element.
  • To be more clear about the "last" member, I just mean index members[members.length-1]

答案1

得分: 1

db.collection.update({},
[
  {
    $set: {
      members: {
        $concatArrays: [
          {
            $slice: [
              "$members",
              {
                $subtract: [ { $size: "$members" }, 1 ]
              }
            ]
          },
          [
            {
              user_id: { $last: "$members.user_id" },
              left_at: "$end_time"
            }
          ]
        ]
      }
    }
  }
],
{ multi: true }
)
英文:
db.collection.update({},
[
  {
    $set: {
      members: {
        $concatArrays: [
          {
            $slice: [
              "$members",
              {
                $subtract: [ { $size: "$members" }, 1 ]
              }
            ]
          },
          [
            {
              user_id: { $last: "$members.user_id" },
              left_at: "$end_time"
            }
          ]
        ]
      }
    }
  }
],
{ multi: true }
)

mongoplayground

huangapple
  • 本文由 发表于 2023年5月21日 03:55:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297101.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定