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()