$split - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$split

Amazon DocumentDB $split 中的彙總運算子用於根據指定的分隔符號,將字串分割為子字串陣列。這對於剖析複雜的字串欄位和擷取個別元件以進行進一步處理非常有用。

參數

  • string:要分割的字串。

  • delimiter:用來分割輸入字串的字元或字串。

範例 (MongoDB Shell)

在此範例中,我們使用 $split將 "Desk" 欄位的元件分隔為 陣列,讓您更輕鬆地處理資料。

建立範例文件

db.people.insertMany([ { "_id": 1, "Desk": "Düsseldorf-BVV-021" }, { "_id": 2, "Desk": "Munich-HGG-32a" }, { "_id": 3, "Desk": "Cologne-ayu-892.50" }, { "_id": 4, "Desk": "Dortmund-Hop-78" } ]);

查詢範例

db.people.aggregate([ { $project: { parts: { $split: ["$Desk", "-"] } } } ]);

輸出

{ "_id" : 1, "parts" : [ "Düsseldorf", "BVV", "021" ] } { "_id" : 2, "parts" : [ "Munich", "HGG", "32a" ] } { "_id" : 3, "parts" : [ "Cologne", "ayu", "892.50" ] } { "_id" : 4, "parts" : [ "Dortmund", "Hop", "78" ] }

的輸出會$split建立陣列,可用於應用程式中以顯示員工的資訊。

程式碼範例

若要檢視使用 $split命令的程式碼範例,請選擇您要使用的語言標籤:

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const result = await db.collection('people').aggregate([ { $project: { parts: { $split: ['$Desk', '-'] } } } ]).toArray(); console.log(result); await client.close(); } example();
Python
from pymongo import MongoClient def example(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client.test result = list(db.people.aggregate([ { '$project': { 'parts': { '$split': ['$Desk', '-'] } } } ])) print(result) client.close() example()