转换为字符串(聚合)
定义
行为
下表列出了可以转换为字符串的输入类型
输入类型 | 行为 |
---|---|
BinData | 返回二进制数据值作为字符串。 |
Boolean | 返回布尔值作为字符串。 |
Double | 返回双精度值作为字符串。 |
Decimal | 返回十进制值作为字符串。 |
Integer | 返回整数值作为字符串。 |
Long | 返回长整数值作为字符串。 |
ObjectId | 返回ObjectId值作为十六进制字符串。 |
String | 无操作。返回字符串值。 |
Date | 返回日期作为字符串。 |
下表列出了一些转换为字符串的示例
示例 | 结果 |
---|---|
{$toString: true} | "true" |
{$toString: false} | "false" |
{$toString: 2.5} | "2.5" |
{$toString: NumberInt(2)} | "2" |
{$toString: NumberLong(1000)} | "1000" |
{$toString: ObjectId("5ab9c3da31c2ab715d421285")} | "5ab9c3da31c2ab715d421285" |
{$toString: ISODate("2018-03-27T16:58:51.538Z")} | "2018-03-27T16:58:51.538Z" |
{ $toString: BinData(4, "hn3f") } | "hn3f" |
示例
创建一个包含以下文档的集合 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
代替。