Definition定义
$toLongConverts a value to a long. If the value cannot be converted to a long,将值转换为long。如果该值无法转换为long,则$toLongerrors. If the value is null or missing,$toLongreturns null.$toLong错误。如果该值为null或缺失,$toLong将返回null。$toLonghas the following syntax:具有以下语法:{
$toLong: <expression>
}The$toLongtakes any valid expression.$toLong接受任何有效表达式。The$toLongis a shorthand for the following$convertexpression:$toLong是以下$convert表达式的简写:{ $convert: { input: <expression>, to: "long" } }Tip
Behavior行为
The following table lists the input types that can be converted to a long:下表列出了可以转换为long的输入类型:
false.false返回Long(0)。true.true返回Long(1)。 | |
| |
| Decimal |
|
| |
| Date |
The following table lists some conversion to long examples:下表列出了一些转换为长示例:
{ $toLong: true } | Long("1") |
{ $toLong: false } | Long("0") |
{ $toLong: 1.99999 } | Long("1") |
{ $toLong: Decimal128("5.5000") } | Long("5") |
{ $toLong: Decimal128("9223372036854775808.0") } | Error |
{ $toLong: Int32(8) } | Long(8) |
{ $toLong: ISODate("2018-03-26T04:38:28.044Z") } | Long("1522039108044") |
{ $toLong: "-2" } | Long("-2") |
{ $toLong: "2.5" } | Error |
{ $toLong: null } | null |
Example示例
Create a collection 使用以下文档创建集合orders with the following documents:orders:
db.orders.insertMany( [
{ _id: 1, item: "apple", qty: Int32(5) },
{ _id: 2, item: "pie", qty: "100" },
{ _id: 3, item: "ice cream", qty: Long("500") },
{ _id: 4, item: "almonds", qty: "50" },
] )
The following aggregation operation on the orders collection converts the qty to long before sorting by the value:orders集合上的以下聚合操作将qty转换为按值排序之前的很久:
// Define stage to add convertedQty field with converted qty value定义阶段以添加具有转换数量值的转换数量字段
qtyConversionStage = {
$addFields: {
convertedQty: { $toLong: "$qty" }
}
};
// Define stage to sort documents by the converted qty values定义按转换后的数量值对文档进行排序的阶段
sortStage = {
$sort: { "convertedQty": -1 }
};
db.orders.aggregate( [
qtyConversionStage,
sortStage
])
The operation returns the following documents:该操作返回以下文档:
{ _id: 3, item: 'ice cream', qty: Long("500"), convertedQty: Long("500") },
{ _id: 2, item: 'pie', qty: '100', convertedQty: Long("100") },
{ _id: 4, item: 'almonds', qty: '50', convertedQty: Long("50") },
{ _id: 1, item: 'apple', qty: 5, convertedQty: Long("5") }
Note
If the conversion operation encounters an error, the aggregation operation stops and throws an error. To override this behavior, use 如果转换操作遇到错误,聚合操作将停止并抛出错误。要覆盖此行为,请改用$convert instead.$converter。