$toInt - Amazon DocumentDB

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

$toInt

4.0 版的新增内容

Amazon DocumentDB 中的$toInt运算符用于将输入值转换为整数数据类型。当您需要确保将字段或表达式表示为整数时,此运算符很有用,这对于某些操作或数据处理任务可能很重要。

参数

  • expression:要转换为整数的表达式。

示例(MongoDB 外壳)

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

创建示例文档

db.numbers.insertMany([ { "name": "one", "value": "1" }, { "name": "hundred", "value": "100" } ]);

查询示例

db.numbers.aggregate([ { $project: { "_id": 0, "name": 1, "intValue": { $toInt: "$value" } }} ]);

输出

{ "name": "one", "intValue": 1 } { "name": "hundred", "intValue": 100 }

代码示例

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

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": 0, "name": 1, "intValue": { $toInt: "$value" } }} ]).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'] collection = db['numbers'] result = list(collection.aggregate([ { "$project": { "_id": 0, "name": 1, "intValue": { "$toInt": "$value" } }} ])) print(result) client.close() example()