本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$trim
4.0 版的新功能
Amazon DocumentDB 中的$trim運算子用於從字串中移除開頭和/或結尾空格字元。
參數
範例 (MongoDB Shell)
下列範例示範如何使用 $trim運算子從字串中移除開頭和結尾空格。
建立範例文件
db.people.insertMany([
{ "name": " John Doe " },
{ "name": " Bob Johnson " }
])
查詢範例
db.people.aggregate([
{ $project: {
"name": { $trim: {input: "$name"}}
}}
])
輸出
[
{ "name": "John Doe" },
{ "name": "Bob Johnson" }
]
程式碼範例
若要檢視使用 $trim命令的程式碼範例,請選擇您要使用的語言標籤:
- 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 collection = db.collection('people');
const result = await collection.aggregate([
{ $project: {
"name": { $trim: {input: "$name" }}
}}
]).toArray();
console.log(result);
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']
collection = db['people']
result = list(collection.aggregate([
{"$project": {
"name": {"$trim": {"input": "$name"}}
}}
]))
print(result)
client.close()
example()