本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$substr
Amazon DocumentDB 中的$substr運算子用於從指定的字串擷取子字串。當您需要根據字元範圍而非位元組範圍來定義子字串時,此功能特別有用。這在處理 Unicode 字串時特別重要,其中用來代表字元的位元組數可能不同。
參數
-
string:要從中擷取子字串的輸入字串。 -
start:要擷取之子字串的起始位置 (以零為基礎)。可以是非負整數表達式。 -
length:擷取子字串中的字元數。可以是非負整數表達式。
範例 (MongoDB Shell)
在此範例中,我們將示範如何使用 從員工的桌面位置$substr擷取狀態縮寫。
建立範例文件
db.people.insertMany([ { "_id": 1, "Desk": "Düsseldorf-NRW-021" }, { "_id": 2, "Desk": "Bremerhaven-HBB-32a" }, { "_id": 3, "Desk": "Norderstedt-SHH-892.50" }, { "_id": 4, "Desk": "Brandenburg-BBB-78" } ]);
查詢範例
db.people.aggregate([ { $project: { "state": { $substr: ["$Desk", 12, 3] } } } ])
輸出
{ "_id": 1, "state": "NRW" },
{ "_id": 2, "state": "HBB" },
{ "_id": 3, "state": "SHH" },
{ "_id": 4, "state": "BBB" }
程式碼範例
若要檢視使用 $substr命令的程式碼範例,請選擇您要使用的語言標籤: