MongoDB 數據類型查詢 — $type使用


MongoDB 使用過程中經常需要根據字段的類型來查詢數據, 而MongoDB中查詢字段類型是通過$type操作符來實現.

$type使用法語:

db.集合名.find({$type:類型值});    //這里的類型值能使用Number也能使用alias

舉個例子:

db.person.find({address:{$type:2}});         //查詢address字段數據類型為字符串
db.person.find({address:{$type:"string"}});  //查詢address字段數據類型為字符串

再舉個有點特殊的查詢,關於null 查詢的例子:

db.person.find({address:null});             //注意,這樣查詢會將沒有 address 列的數據一並查詢出來
db.person.find({address:{$exists:true, $eq:null}}); //這樣查詢的是 address 列值為null 的數據
db.person.find({address:{$type:10}});      //這樣查詢的是 address 列值為null 的數據

$type 有效的類型值,如下:

Type Number Alias Notes
Double 1 “double”
String 2 “string”
Object 3 “object”
Array 4 “array”
Binary data 5 “binData”
Undefined 6 “undefined” Deprecated.
ObjectId 7 “objectId”
Boolean 8 “bool”
Date 9 “date”
Null 10 “null”
Regular Expression 11 “regex”
DBPointer 12 “dbPointer” Deprecated.
JavaScript 13 “javascript”
Symbol 14 “symbol” Deprecated.
JavaScript (with scope) 15 “javascriptWithScope”
32-bit integer 16 “int”
Timestamp 17 “timestamp”
64-bit integer 18 “long”
Decimal128 19 “decimal” New in version 3.4.
Min key -1 “minKey”
Max key 127 “maxKey”

官網參考:https://docs.mongodb.com/manual/reference/operator/query/type/index.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM