$ltrim - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$ltrim

4.0 版的新增内容。

弹性集群不支持。

Amazon DocumentDB 中的$ltrim运算符用于从字符串中删除前导字符。默认情况下,它会删除前导空格字符,但您也可以通过传递 chars 参数来指定一组要删除的字符。

参数

  • input:要从中删除前导空格字符的输入字符串。

  • chars:(可选)删除特定字符。

示例(MongoDB 外壳)

以下示例演示了从字符串开头删除指定字符 (” *”) 的用法。$ltrim

创建示例文档

db.collection.insertMany([ { name: " *John Doe", age: 30 }, { name: "Jane Doe*", age: 25 }, { name: " Bob Smith ", age: 35 } ]);

查询示例

db.collection.aggregate([ { $project: { _id: 0, name: { $ltrim: { input: "$name", chars: " *" } }, age: 1 } } ]);

输出

[ { "name": "John Doe", "age": 30 }, { "name": "Jane Doe ", "age": 25 }, { "name": "Bob Smith ", "age": 35 } ]

代码示例

要查看使用该$ltrim命令的代码示例,请选择要使用的语言的选项卡:

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'); try { await client.connect(); const db = client.db('test'); const collection = db.collection('collection'); const pipeline = [ { $project: { _id: 0, name: { $ltrim: { input: '$name', chars: ' *' } }, age: 1 } } ]; const result = await collection.aggregate(pipeline).toArray(); console.dir(result, { depth: null }); } finally { await client.close(); } } example().catch(console.error);
Python
from pymongo import MongoClient def example(): try: 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.collection pipeline = [ { "$project": { "_id": 0, "name": { "$ltrim": { "input": "$name", "chars": " *" } }, "age": 1 } } ] results = collection.aggregate(pipeline) for doc in results: print(doc) except Exception as e: print(f"An error occurred: {e}") finally: client.close() example()