跳到主要内容

MongoDB $type 操作符


描述

在本章节中,我们将继续讨论MongoDB中条件操作符 $type。

$type操作符是基于BSON类型来检索集合中匹配的数据类型,并返回结果。

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

**类型****数字****备注**
Double1
String2
Object3
Array4
Binary data5
Undefined6已废弃。
Object id7
Boolean8
Date9
Null10
Regular Expression11
JavaScript13
Symbol14
JavaScript (with scope)15
32-bit integer16
Timestamp17
64-bit integer18
Min key255Query with -1 .
Max key127
**我们使用的数据库名称为"lectcode" 我们的集合名称为"col",以下为我们插入的数据。**

简单的集合"col":

>db.col.insert({

title: 'PHP 教程',

description: 'PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。',

by: '集码教程',

url: 'http://www.lectcode.com',

tags: ['php'],

likes: 200

})

db.col.insert({title: 'Java 教程', 

description: 'Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。',

by: '集码教程',

url: 'http://www.lectcode.com',

tags: ['java'],

likes: 150

})

>db.col.insert({title: 'MongoDB 教程', 

description: 'MongoDB 是一个 Nosql 数据库',

by: '集码教程',

url: 'http://www.lectcode.com',

tags: ['mongodb'],

likes: 100

})

使用find()命令查看数据:

> db.col.find()

{ "_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP 教程", "description" : "PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。", "by" : "集码教程", "url" : "http://www.lectcode.com", "tags" : [ "php" ], "likes" : 200 }

{ "_id" : ObjectId("56066549ade2f21f36b0313b"), "title" : "Java 教程", "description" : "Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。", "by" : "集码教程", "url" : "http://www.lectcode.com", "tags" : [ "java" ], "likes" : 150 }

{ "_id" : ObjectId("5606654fade2f21f36b0313c"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "集码教程", "url" : "http://www.lectcode.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.lectcode.com", "tags" : [ "php" ], "likes" : 200 }

{ "_id" : ObjectId("56066549ade2f21f36b0313b"), "title" : "Java 教程", "description" : "Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。", "by" : "集码教程", "url" : "http://www.lectcode.com", "tags" : [ "java" ], "likes" : 150 }

{ "_id" : ObjectId("5606654fade2f21f36b0313c"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "集码教程", "url" : "http://www.lectcode.com", "tags" : [ "mongodb" ], "likes" : 100 }