MongoDb使用数组键上的乘法更新数组元素
我有一份mongo文件如下MongoDb使用数组键上的乘法更新数组元素,mongodb,Mongodb,我有一份mongo文件如下 { "id": "mongoId", "results": [ "score" : 80, "details": { "credit": 2, "creditPoints": 40, "creditScore": 0 } ] }
{
"id": "mongoId",
"results": [
"score" : 80,
"details": {
"credit": 2,
"creditPoints": 40,
"creditScore": 0
}
]
}
我想将所有文档更新为creditScore
为credit*creditPoints
到目前为止,我所尝试的是
db.match.updateMany({}, { "$set" : { "results.$[].details.creditScore": {"$mul" : { "$results.details.credit": "$results.details.creditPoints" } } }} );
直接更新不允许使用内部字段操作,您需要从MongoDB 4.2开始使用
迭代$map
数组结果的循环
乘以$multiply
和积分
积分
将$mergeObjects
对象与更新的详细信息
字段合并信用评分
将当前对象与更新的$mergeObjects
对象合并详细信息
db.match.updateMany({},
[
{
$set: {
results: {
$map: {
input: "$results",
in: {
$mergeObjects: [
"$$this",
{
details: {
$mergeObjects: [
"$$this.details",
{
creditScore: {
$multiply: [
"$$this.details.credit",
"$$this.details.creditPoints"
]
}
}
]
}
}
]
}
}
}
}
}
])