Definition定义
$toStringConverts a value to a string. If the value cannot be converted to a string,将值转换为字符串。如果值无法转换为字符串,则$toStringerrors. If the value is null or missing,$toStringreturns null.$toString错误。如果该值为null或缺失,$toString将返回null。$toStringhas the following syntax:具有以下语法:{
$toString: <expression>
}The$toStringtakes any valid expression.$toString接受任何有效的表达式。The$toStringis a shorthand for the following$convertexpression:$toString是以下$convert表达式的简写:{ $convert: { input: <expression>, to: "string" } }
Behavior行为
The following table lists the input types that can be converted to a string:下表列出了可以转换为字符串的输入类型:
| BinData | |
| Decimal | |
| ObjectId | |
| Date |
The following table lists some conversion to string examples:下表列出了一些转换为字符串的示例:
{$toString: true} | "true" |
{$toString: false} | "false" |
{$toString: 2.5} | "2.5" |
{$toString: Int32(2)} | "2" |
{$toString: Long(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" |
Example示例
Create a collection 使用以下文档创建集合orders with the following documents: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 },
] )
The following aggregation operation on the orders collection converts the zipcode to string before sorting by the string value: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
] )
The operation returns the following documents:该操作返回以下文档:
{
_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'
}
Note
If the conversion operation encounters an error, the aggregation operation stops and throws an error. To override this behavior, use 如果转换操作遇到错误,聚合操作将停止并抛出错误。要覆盖此行为,请改用$convert instead.$convert。