本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$mul
Amazon DocumentDB 中的$mul運算子用於將欄位的值乘以指定的數字。這對於以原子方式和一致的方式更新多個文件非常有用,例如根據信用卡狀態更新飛行里程。
參數
-
field:要乘以的欄位。 -
multiplier:要將欄位值乘以的數字。
範例 (MongoDB Shell)
此範例示範如何使用 $mul 運算子,將 credit_card 欄位為 之所有文件flight_miles的值加倍true。
建立範例文件
db.miles.insertMany([ { "_id": 1, "member_since": new Date("1987-01-01"), "credit_card": false, "flight_miles": [1205, 2560, 880] }, { "_id": 2, "member_since": new Date("1982-01-01"), "credit_card": true, "flight_miles": [2410, 5120, 1780, 5560] }, { "_id": 3, "member_since": new Date("1999-01-01"), "credit_card": true, "flight_miles": [2410, 1760] } ]);
查詢範例
db.miles.update( { "credit_card": { "$eq": true } }, { "$mul": { "flight_miles.$[]": NumberInt(2) } }, { "multi": true } );
輸出
{ "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "flight_miles" : [ 1205, 2560, 880 ] }
{ "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 4820, 10240, 3560, 11120 ] }
{ "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 4820, 3520 ] }
對於有信用卡的客戶,他們的飛行里程已加倍。
$[] 位置陣列運算子用於將 $mul操作套用至flight_miles陣列中的每個元素。
程式碼範例
若要檢視使用 $mul命令的程式碼範例,請選擇您要使用的語言標籤: