top
Loading...
MongoDB $type 操作符

MongoDB $type 操作符


描述

在本章節中,我們將繼續討論MongoDB中條件操作符 $type。

$type操作符是基於BSON類型來檢索集合中匹配的數據類型,併返回結果。

MongoDB 中可以使用的類型如下表所示:

類型 數字 備注
Double 1  
String 2  
Object 3  
Array 4  
Binary data 5  
Undefined 6 已廢棄。
Object id 7  
Boolean 8  
Date 9  
Null 10  
Regular Expression 11  
JavaScript 13  
Symbol 14  
JavaScript (with scope) 15  
32-bit integer 16  
Timestamp 17  
64-bit integer 18  
Min key 255 Query with -1.
Max key 127  

我們使用的數據庫名稱為"runoob" 我們的集合名稱為"col",以下為我們插入的數據。

簡單的集合"col":

>db.col.insert({
    title: 'PHP 教程', 
    description: 'PHP 是一種創建動態交互性站點的強有力的服務器端腳本語言。',
    by: '教程',
    url: 'http://www.sharebody.com',
    tags: ['php'],
    likes: 200
})

>db.col.insert({title: 'Java 教程', 
    description: 'Java 是由Sun Microsystems公司於1995年5月推出的高級程序設計語言。',
    by: '教程',
    url: 'http://www.sharebody.com',
    tags: ['java'],
    likes: 150
})

>db.col.insert({title: 'MongoDB 教程', 
    description: 'MongoDB 是一個 Nosql 數據庫',
    by: '教程',
    url: 'http://www.sharebody.com',
    tags: ['mongodb'],
    likes: 100
})

使用find()命令查看數據:

> db.col.find()
{ "_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP 教程", "description" : "PHP 是一種創建動態交互性站點的強有力的服務器端腳本語言。", "by" : "教程", "url" : "http://www.sharebody.com", "tags" : [ "php" ], "likes" : 200 }
{ "_id" : ObjectId("56066549ade2f21f36b0313b"), "title" : "Java 教程", "description" : "Java 是由Sun Microsystems公司於1995年5月推出的高級程序設計語言。", "by" : "教程", "url" : "http://www.sharebody.com", "tags" : [ "java" ], "likes" : 150 }
{ "_id" : ObjectId("5606654fade2f21f36b0313c"), "title" : "MongoDB 教程", "description" : "MongoDB 是一個 Nosql 數據庫", "by" : "教程", "url" : "http://www.sharebody.com", "tags" : [ "mongodb" ], "likes" : 100 }

MongoDB 操作符 - $type 實例

如果想獲取 "col" 集合中 title 為 String 的數據,你可以使用以下命令:

db.col.find({"title" : {$type : 2}})
或
db.col.find({"title" : {$type : 'string'}})

輸出結果為:

{ "_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP 教程", "description" : "PHP 是一種創建動態交互性站點的強有力的服務器端腳本語言。", "by" : "教程", "url" : "http://www.sharebody.com", "tags" : [ "php" ], "likes" : 200 }
{ "_id" : ObjectId("56066549ade2f21f36b0313b"), "title" : "Java 教程", "description" : "Java 是由Sun Microsystems公司於1995年5月推出的高級程序設計語言。", "by" : "教程", "url" : "http://www.sharebody.com", "tags" : [ "java" ], "likes" : 150 }
{ "_id" : ObjectId("5606654fade2f21f36b0313c"), "title" : "MongoDB 教程", "description" : "MongoDB 是一個 Nosql 數據庫", "by" : "教程", "url" : "http://www.sharebody.com", "tags" : [ "mongodb" ], "likes" : 100 }
北斗有巢氏 有巢氏北斗