定义
行为
下表列出了可转换为字符串的输入类型:
输入类型 | 行为 |
|---|---|
阵列 | 以字符串形式返回 8.3版本新增。 |
BinData | 如果 |
布尔 | 以字符串形式返回布尔值。 |
Date | 以字符串形式返回 |
Decimal 数据类型 |
|
double |
|
整型 |
|
Long |
|
Max key | 以字符串形式返回 8.3版本新增。 |
最小键值 | 以字符串形式返回 8.3版本新增。 |
对象 | 以字符串形式返回该对象。 8.3版本新增。 |
ObjectId | 以十六进制字符串形式返回 |
正则表达式 | 以字符串形式返回 8.3版本新增。 |
字符串 | 无需操作。返回字符串值。 |
时间戳 | 以字符串形式返回 8.3版本新增。 |
提示
要转换 以外的字符串,请使用10 $convertbase和 选项。
下表列出了转换为字符串的部分示例:
例子 | 结果 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8.3版本新增。 |
|
8.3版本新增。 |
|
8.3版本新增。 |
|
8.3版本新增。 |
|
8.3版本新增。 |
|
8.3版本新增。 |
例子
使用以下文档创建集合 orders:
db.orders.insertMany( [ { _id: 1, item: "apple", qty: 5, zipcode: 93445 }, { _id: 2, item: "almonds", qty: 2, zipcode: "12345-0030" }, { _id: 3, item: "peaches", qty: 5, zipcode: 12345 }, ] )
orders 集合上的以下聚合操作会在按字符串值排序之前将 zipcode 转换为字符串:
// Define stage to add convertedZipCode field with the converted zipcode value zipConversionStage = { $addFields: { convertedZipCode: { $toString: "$zipcode" } } }; // Define stage to sort documents by the converted zipcode sortStage = { $sort: { "convertedZipCode": 1 } }; db.orders.aggregate( [ zipConversionStage, sortStage ] )
该操作将返回以下文档:
{ _id: 3, item: 'peaches', qty: 5, zipcode: 12345, convertedZipCode: '12345' }, { _id: 2, item: 'almonds', qty: 2, zipcode: '12345-0030', convertedZipCode: '12345-0030' }, { _id: 1, item: 'apple', qty: 5, zipcode: 93445, convertedZipCode: '93445' }
注意
如果转换操作遇到错误,聚合操作会停止并抛出错误。要覆盖此行为,请改为使用 $convert。