翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$toBool
Amazon DocumentDB の $toBool演算子は、式をブール値に変換します。
パラメータ
注: 文字列は に変換されますtrue。
例 (MongoDB シェル)
次の例は、 $toBool演算子を使用して、さまざまなデータ型からデバイス状態値を正規化する方法を示しています。
サンプルドキュメントを作成する
db.deviceStates.insertMany([
{ _id: 1, deviceId: "sensor-001", status: true },
{ _id: 2, deviceId: "camera-002", status: 1 },
{ _id: 3, deviceId: "thermostat-003", status: "active" },
{ _id: 4, deviceId: "doorlock-004", status: 0 }
]);
クエリの例
db.deviceStates.aggregate([
{
$project: {
_id: 1,
deviceId: 1,
isActive: { $toBool: "$status" }
}
}
]);
出力
[
{ "_id": 1, "deviceId": "sensor-001", "isActive": true },
{ "_id": 2, "deviceId": "camera-002", "isActive": true },
{ "_id": 3, "deviceId": "thermostat-003", "isActive": true },
{ "_id": 4, "deviceId": "doorlock-004", "isActive": false }
]
コードの例
$toBool コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。
- Node.js
-
const { MongoClient } = require('mongodb');
async function main() {
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('deviceStates');
const result = await collection.aggregate([
{
$project: {
_id: 1,
deviceId: 1,
isActive: { $toBool: '$status' }
}
}
]).toArray();
console.log(result);
await client.close();
}
main();
- Python
-
from pymongo import MongoClient
def main():
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['deviceStates']
result = list(collection.aggregate([
{
'$project': {
'_id': 1,
'deviceId': 1,
'isActive': { '$toBool': '$status' }
}
}
]))
print(result)
client.close()
if __name__ == '__main__':
main()