$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 |
我们使用的数据库名称为 "appblog",集合名称为 "col"
插入以下数据
> db.col.insert({
title: 'PHP',
description: 'PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。',
by: 'APP开发技术博客',
url: 'http://www.appblog.cn',
tags: ['php'],
likes: 200
})
> db.col.insert({title: 'Java',
description: 'Java 是由Sun公司于1995年5月推出的高级程序设计语言。',
by: 'APP开发技术博客',
url: 'http://www.appblog.cn',
tags: ['java'],
likes: 150
})
> db.col.insert({title: 'MongoDB',
description: 'MongoDB 是一个 Nosql 数据库',
by: 'APP开发技术博客',
url: 'http://www.appblog.cn',
tags: ['mongodb'],
likes: 100
})
使用find()命令查看数据:
> db.col.find()
{ "_id" : ObjectId("5aefe63c2d2577acadf1e0d2"), "title" : "PHP", "description" : "PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。", "by" : "APP开发技术博客", "url" : "http://www.appblog.cn", "tags" : [ "php" ], "likes" : 200 }
{ "_id" : ObjectId("5aefe6462d2577acadf1e0d3"), "title" : "Java", "description" : "Java 是由Sun公司于1995年5月推出的高级程序设计语言。", "by" : "APP开发技术博客", "url" : "http://www.appblog.cn", "tags" : [ "java" ], "likes" : 150 }
{ "_id" : ObjectId("5aefe64f2d2577acadf1e0d4"), "title" : "MongoDB", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "APP开发技术博客", "url" : "http://www.appblog.cn", "tags" : [ "mongodb" ], "likes" : 100 }
MongoDB 操作符 – $type 实例
如果想获取 "col" 集合中 title 为 String 的数据,你可以使用以下命令:
db.col.find({"title" : {$type : 2}})
输出结果为:
> db.col.find({"title" : {$type : 2}})
{ "_id" : ObjectId("5aefe63c2d2577acadf1e0d2"), "title" : "PHP", "description" : "PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。", "by" : "APP开发技术博客", "url" : "http://www.appblog.cn", "tags" : [ "php" ], "likes" : 200 }
{ "_id" : ObjectId("5aefe6462d2577acadf1e0d3"), "title" : "Java", "description" : "Java 是由Sun公司于1995年5月推出的高级程序设计语言。", "by" : "APP开发技术博客", "url" : "http://www.appblog.cn", "tags" : [ "java" ], "likes" : 150 }
{ "_id" : ObjectId("5aefe64f2d2577acadf1e0d4"), "title" : "MongoDB", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "APP开发技术博客", "url" : "http://www.appblog.cn", "tags" : [ "mongodb" ], "likes" : 100 }
>




