英文:
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 }
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论