【MongoDB】查看文档(元素查询)$type
$ type选择字段值为指定BSON类型实例的文档。 在处理数据类型不可预测的高度非结构化数据时,通过数据类型进行查询非常有用。
1 |
{ field: { $type: <BSON type number> | <String alias> } } |
1:可用类型
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” |
2:测试数据
1 2 3 4 5 6 7 8 9 10 11 12 13 |
> db.t.find() { "_id" : ObjectId("5982b8b2c566b07b8733e787"), "a" : 5, "b" : 5, "c" : null } { "_id" : ObjectId("5982b8b2c566b07b8733e788"), "a" : 3, "b" : null, "c" : 8 } { "_id" : ObjectId("5982b8b2c566b07b8733e789"), "a" : null, "b" : 3, "c" : 9 } { "_id" : ObjectId("5982b8b2c566b07b8733e78a"), "a" : 1, "b" : 2, "c" : 3 } { "_id" : ObjectId("5982b8b2c566b07b8733e78b"), "a" : 2, "c" : 5 } { "_id" : ObjectId("5982b8b2c566b07b8733e78c"), "a" : 3, "b" : 2 } { "_id" : ObjectId("5982b8b2c566b07b8733e78d"), "a" : 4 } { "_id" : ObjectId("5982b8b2c566b07b8733e78e"), "b" : 2, "c" : 4 } { "_id" : ObjectId("5982b8b2c566b07b8733e78f"), "b" : 2 } { "_id" : ObjectId("5982b8b3c566b07b8733e790"), "c" : 6 } { "_id" : ObjectId("5982c220c566b07b8733e791"), "a" : "guan", "b" : "yu", "c" : "guanyunchang" } > |
3:查看集合t中a为string的文档
1 2 3 4 5 6 7 8 |
# 使用专属数值进行过滤 > db.t.find({a: {$type: 2}}) { "_id" : ObjectId("5982c220c566b07b8733e791"), "a" : "guan", "b" : "yu", "c" : "guanyunchang" } > # 或者使用别名 > db.t.find({a: {$type: "string"}}) { "_id" : ObjectId("5982c220c566b07b8733e791"), "a" : "guan", "b" : "yu", "c" : "guanyunchang" } > |
4:查看集合t中a为数值的文档
1 2 3 4 5 6 7 8 |
> db.t.find({a: {$type: 1}}) { "_id" : ObjectId("5982b8b2c566b07b8733e787"), "a" : 5, "b" : 5, "c" : null } { "_id" : ObjectId("5982b8b2c566b07b8733e788"), "a" : 3, "b" : null, "c" : 8 } { "_id" : ObjectId("5982b8b2c566b07b8733e78a"), "a" : 1, "b" : 2, "c" : 3 } { "_id" : ObjectId("5982b8b2c566b07b8733e78b"), "a" : 2, "c" : 5 } { "_id" : ObjectId("5982b8b2c566b07b8733e78c"), "a" : 3, "b" : 2 } { "_id" : ObjectId("5982b8b2c566b07b8733e78d"), "a" : 4 } > |