$convert - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$convert

バージョン 4.0 の新機能

Amazon DocumentDB の $convert演算子は、あるデータ型から別のデータ型に値を変換するために使用されます。この演算子は、文字列を数値に変換したり、日付をタイムスタンプに変換したりするなど、さまざまなタイプのデータに対してオペレーションを実行する必要がある場合に便利です。

パラメータ

  • to: 値を変換するターゲットデータ型。サポートされている値は "string""double""long""int""date""boolean" です。

  • from: 値の現在のデータ型。指定しない場合、Amazon DocumentDB はデータ型を自動的に検出しようとします。

  • onError: (オプション) 変換が失敗した場合に返される値。特定の値、または次の特殊な値のいずれかを指定できます: "null""zerofill"、または "error"

  • onNull: (オプション) 入力値が の場合に返される値null。特定の値、または次の特殊な値のいずれかを指定できます: "null""zerofill"、または "error"

例 (MongoDB シェル)

次の例は、 $convert演算子を使用して文字列値を日付に変換する方法を示しています。

サンプルドキュメントを作成する

db.users.insertMany([ { _id: 1, name: "John Doe", joinedOn: "2022-01-01" }, { _id: 2, name: "Jane Smith", joinedOn: "2023-02-15" }, { _id: 3, name: "Bob Johnson", joinedOn: "invalid date" } ]);

クエリの例

db.users.aggregate([ { $project: { _id: 1, name: 1, joinedOn: { $convert: { input: "$joinedOn", to: "date", onError: "null", onNull: "null" } } } } ])

出力

[ { "_id" : 1, "name" : "John Doe", "joinedOn" : ISODate("2022-01-01T00:00:00Z") }, { "_id" : 2, "name" : "Jane Smith", "joinedOn" : ISODate("2023-02-15T00:00:00Z") }, { "_id" : 3, "name" : "Bob Johnson", "joinedOn" : null } ]

コードの例

$convert コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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 users = db.collection("users"); const results = await users.aggregate([ { $project: { _id: 1, name: 1, joinedOn: { $convert: { input: "$joinedOn", to: "date", onError: "null", onNull: "null" } } } } ]).toArray(); console.log(results); 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"] users = db["users"] results = list(users.aggregate([ { "$project": { "_id": 1, "name": 1, "joinedOn": { "$convert": { "input": "$joinedOn", "to": "date", "onError": "null", "onNull": "null" } } } } ])) print(results) client.close() example()