在这种要求中使用$mul的正确原型是什么?



我是MongoDB的新手,我想将"增加"数组的"rate2"提高100%。 它位于我的"CUSTOMER.ratings"文档中,其中的名字是"Jimmy"。

集合是这样的:

db.collection.insert(
{
"CUSTOMER": {
"first name": "Jimmy",
"ratings": [{"increase": {"rate":99},  {"increase": {"rate2": 20.5}}]
}
}
); 

我尝试了以下内容,但它创建了一个新集合,而不是将新地址放入位置数组中:

db.collection.update({"CUSTOMER.first name": "Jimmy"}, {$mul:{"ratings":{"increase":{ "rate2": 2 }}}}); 

我试图将"评级"放在$mul之前,但它不起作用。

我需要做这样的事情的正确原型。

预期结果如下:

db.collection.insert(
{
"CUSTOMER": {
"first name": "Jimmy",
"ratings": [{{"increase": "rate": 99}},
{"increase": "rate": 41}}
]
}
}
); 

综上所述,我想将 rate2 提高 100%。

为不混淆,请考虑以下事项:

A 
B[
C {rate}
C {rate2} ]

那么如何乘以"rate2"的值呢?

I tried {$mul: {"A":{"B":{"C":2 }}}}; 
Also, I tried {$mul: {"A.B.C": 2}};
Also, I tried {"A.B": {$mul: {"C": 2}}};

另外,我已经使用了$pull和$push原型,但不确定为什么不起作用!!

考虑输入文档:

{
"_id" : 1,
"CUSTOMER" : {
"first name" : "Jimmy",
"ratings" : [
{
"increase" : {
"rate" : 99
}
},
{
"increase" : {
"rate2" : 20.5
}
}
]
}
}

以下查询将更新文档并将嵌套字段乘以(乘2并更新(rate2("CUSTOMER.ratings.increase.rate2"(。

db.collection.updateOne(
{ _id: 1 },
{ $mul: { "CUSTOMER.ratings.$[e].increase.rate2": 2 } },
{ arrayFilters: [ { "e.increase.rate2": { $exists: true } } ] }
)

请注意arrayFilters和过滤的位置运算符 $[some_id] 的用法(用于更新特定数组元素,如arrayFilters条件中所述(。


[编辑添加]

另一种更新方式:使用位置 $ update 运算符进行更新:

db.collection.updateOne(
{ "CUSTOMER.ratings.increase.rate2": { $exists: true } },
{ $mul: { "CUSTOMER.ratings.$.increase.rate2": 2 } }
)

最新更新