MongoDB聚合運算符$toBool詳解
MongoDB聚合運算符:$toBool
$toBool
聚合運算符將指定的值轉換為布爾類型boolean。
語法
{ $toBool: <expression> }
$toBool
接受任何有效的表達式。
$toBool
是$convert
表達式的簡寫形式:
{ $convert: { input: <expression>, to: "bool" } }
使用
下表列出了可轉換為布爾值的類型:
輸入類型 | 規(guī)則 |
---|---|
Array | 返回ture |
Binary data | Returns true |
Boolean | 直接返回 |
Code | 返回true |
Date | 返回true |
Decimal | 0返回false,非0返回true |
Double | 0返回false,非0返回true |
Integer | 0返回false,非0返回true |
JavaScript | 返回true |
Long | 0返回false,非0返回true |
MaxKey | 返回true |
MinKey | 返回true |
Null | 返回null |
Object | 返回true |
ObjectId | 返回true |
Regular expression | 返回true |
String | 返回true |
Timestamp | 返回true |
下表列出了一些轉換為布爾值的示例:
示例 | 結果 |
---|---|
{$toBool: false} | false |
{$toBool: 1.99999} | true |
{$toBool: NumberDecimal("5")} | true |
{$toBool: NumberDecimal("0")} | false |
{$toBool: 100} | true |
{$toBool: ISODate("2018-03-26T04:38:28.044Z")} | true |
{$toBool: "false"} | true |
{$toBool: ""} | true |
{$toBool: null} | null |
舉例
使用下面的腳本創(chuàng)建orders
集合:
db.orders.insertMany( [ { _id: 1, item: "apple", qty: 5, shipped: true }, { _id: 2, item: "pie", qty: 10, shipped: 0 }, { _id: 3, item: "ice cream", shipped: 1 }, { _id: 4, item: "almonds", qty: 2, shipped: "true" }, { _id: 5, item: "pecans", shipped: "false" }, //注意:所有的字符串都轉換為true { _id: 6, item: "nougat", shipped: "" } //注意:所有的字符串都轉換為true ] )
下面是對訂單集合orders
的聚合操作,先將已發(fā)貨的訂單shipped
轉換為布爾值,然后再查找未發(fā)貨的訂單:
//定義shippedConversionStage階段,添加轉換后的發(fā)貨標志字段`convertedShippedFlag` //因為所有的字符串都會被轉換為true,所以要對字符串"false"做個特殊處理 shippedConversionStage = { $addFields: { convertedShippedFlag: { $switch: { branches: [ { case: { $eq: [ "$shipped", "false" ] }, then: false } , { case: { $eq: [ "$shipped", "" ] }, then: false } ], default: { $toBool: "$shipped" } } } } }; // 定義文檔過濾階段,過濾出沒有發(fā)貨的訂單 unshippedMatchStage = { $match: { "convertedShippedFlag": false } }; db.orders.aggregate( [ shippedConversionStage, unshippedMatchStage ] )
執(zhí)行的結果為:
{ "_id" : 2, "item" : "pie", "qty" : 10, "shipped" : 0, "convertedShippedFlag" : false }
{ "_id" : 5, "item" : "pecans", "shipped" : "false", "convertedShippedFlag" : false }
{ "_id" : 6, "item" : "nougat", "shipped" : "", "convertedShippedFlag" : false }
到此這篇關于MongoDB聚合運算符:$toBool的文章就介紹到這了,更多相關MongoDB聚合運算符內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
ubuntu安裝mongodb創(chuàng)建賬號和庫及添加坐標索引的流程分析
這篇文章主要介紹了ubuntu安裝mongodb創(chuàng)建賬號和庫及添加坐標索引的流程分析,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10MongoDb的"not master and slaveok=false"錯誤及解決方法
今天小編就為大家分享一篇關于MongoDb的"not master and slaveok=false"錯誤及解決方法,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-10-10在Linux服務器中配置mongodb環(huán)境的步驟
這篇文章主要介紹了在Linux服務器中配置mongodb環(huán)境的步驟,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07