注意:与<{3}}问有关,因为它们不包含数组过滤器匹配项。 < / p>
我有以下查询:
db.UserNotifications.updateOne(
{_id:ObjectId("5c5c39e94c9d4404d4577e94")},
{$set:{
"Notifications.$[match].Group.ActualUnreadCount": 50,
"Notifications.$[match].Group.UnreadCountSnapshot": "Notifications.$[match].Group.ActualUnreadCount"
}},
{arrayFilters:[{
"match.Group.Id": "some-id"
}]});
现在,我要做的是将数组中匹配项的UnreadCountSnapshot
的值设置为相同匹配项的ActualUnreadCount
的值。
相反,UnreadCountSnapshot
仅设置为字符串"Notifications.$[match].Group.ActualUnreadCount"
。
关于如何实现这一点的任何想法?
以下是集合中的示例文档:
{
"_id": {
"$oid": "5c5c39e94c9d4404d4577e94"
},
"Notifications": [{
"Object": {
"_id": "5e3967cc9fc5720001d7100f",
"Type": "Transaction"
},
"Change": {
"Verb": "Create",
"TimeUtc": {
"$date": "2020-02-04T12:47:08.796Z"
},
"Actors": []
},
"Group": {
"TotalCount": 2,
"ActualUnreadCount": 50,
"UnreadCountSnapshot": 23,
"ReadTimeUtc": {
"$date": "2020-08-26T10:24:32.602Z"
},
"ViewTimeUtc": {
"$date": "2020-08-26T10:24:32.602Z"
}
}
}],
"LastNotificationTimeUtc": {
"$date": "2019-02-21T10:18:57.456Z"
},
"LastDeletedNotificationTimeUtc": {
"$date": "2020-08-26T10:24:30.374Z"
}
}
答案 0 :(得分:1)
arrayFields
不允许将任何参考字段值分配给另一个字段,您可以使用MongoDB v4.2中的update document with aggregation pipeline,
db.UserNotifications.updateOne(
{ _id: ObjectId("5c5c39e94c9d4404d4577e94") },
[{
$set: {
Notifications: {
$map: {
input: "$Notifications",
in: {
$mergeObjects: [
"$$this",
{
$cond: [{
$eq: [
"$$this.Object._id",
"5e3967cc9fc5720001d7100f" // some id
]
},
{
Group: {
$mergeObjects: [
"$$this.Group",
{
ActualUnreadCount: 50, // add update number
UnreadCountSnapshot: "$$this.Group.ActualUnreadCount"
}
]
}
},
{}
]
}
]
}
}
}
}
}]
)