$toString - Amazon DocumentDB

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

$toString

4.0 版的新增内容

Amazon DocumentDB 中的$toString运算符用于将任何类型的值(空值除外)转换为字符串表示形式。当您需要对最初不是字符串格式的值执行字符串操作时,这可能很有用。

参数

  • expression: 要转换为字符串的表达式。

示例(MongoDB 外壳)

以下示例演示如何使用$toString运算符将数值转换为字符串。

创建示例文档

db.numbers.insertMany([ { "_id": 1, "value": 42 }, { "_id": 2, "value": 3.14 } ]);

查询示例

db.numbers.aggregate([ { $project: { _id: 1, valueAsString: { $toString: "$value" } }} ]);

输出

{ "_id": 1, "valueAsString": "42" } { "_id": 2, "valueAsString": "3.14" }

代码示例

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

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('numbers'); const result = await collection.aggregate([ { $project: { _id: 1, valueAsString: { $toString: '$value' } }} ]).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['numbers'] result = list(collection.aggregate([ { '$project': { '_id': 1, 'valueAsString': { '$toString': '$value' } }} ])) print(result) client.close() example()