View a markdown version of this page

$isNumber - Amazon DocumentDB

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

$isNumber

8.0.1 版中的新增内容。

Amazon DocumentDB 中的$isNumber运算符返回一个布尔值,表示给定表达式是否解析为数字类型(整数、十进制、双精度、长整数)。请注意,即使数组中的所有元素都是数字,数组也不被视为数字。例如,$isNumber应用于[1, 2, 3]返回值false

参数

  • expression:任何用于检查其是否解析为数字类型的表达式。

示例(MongoDB Shell)

以下示例说明如何使用$isNumber运算符检查字段值是否为数值。

创建示例文档

db.data.insertMany([ {_id: 1, value: 42}, {_id: 2, value: "hello"}, {_id: 3, value: 3.14}, {_id: 4, value: null} ]);

查询示例

db.data.aggregate([ { $project: { isNum: { $isNumber: "$value" } } } ]);

输出

[ {_id: 1, isNum: true}, {_id: 2, isNum: false}, {_id: 3, isNum: true}, {_id: 4, isNum: false} ]

代码示例

要查看使用$isNumber运算符的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = new MongoClient('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('data'); const result = await collection.aggregate([ { $project: { isNum: { $isNumber: "$value" } } } ]).toArray(); console.log(result); } finally { 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') try: db = client['test'] collection = db['data'] result = list(collection.aggregate([ {'$project': {'isNum': {'$isNumber': '$value'}}} ])) print(result) finally: client.close() example()