$轉換 - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$轉換

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

下列範例示範使用 $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()