1 描述

在本章节中,我们将继续讨论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”:

  1. >db.col.insert({
  2. title: 'PHP 教程',
  3. description: 'PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。',
  4. by: '菜鸟教程',
  5. url: 'http://www.runoob.com',
  6. tags: ['php'],
  7. likes: 200
  8. })
  9. >db.col.insert({title: 'Java 教程',
  10. description: 'Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。',
  11. by: '菜鸟教程',
  12. url: 'http://www.runoob.com',
  13. tags: ['java'],
  14. likes: 150
  15. })
  16. >db.col.insert({title: 'MongoDB 教程',
  17. description: 'MongoDB 是一个 Nosql 数据库',
  18. by: '菜鸟教程',
  19. url: 'http://www.runoob.com',
  20. tags: ['mongodb'],
  21. likes: 100
  22. })

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

  1. > db.col.find()
  2. {
  3. "_id": "56066542ade2f21f36b0313a",
  4. "title": "PHP 教程",
  5. "description": "PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。",
  6. "by": "菜鸟教程",
  7. "url": "http://www.runoob.com",
  8. "tags": [
  9. "php"
  10. ],
  11. "likes": 200
  12. }
  13. {
  14. "_id": "56066549ade2f21f36b0313b",
  15. "title": "Java 教程",
  16. "description": "Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。",
  17. "by": "菜鸟教程",
  18. "url": "http://www.runoob.com",
  19. "tags": [
  20. "java"
  21. ],
  22. "likes": 150
  23. }
  24. {
  25. "_id": "5606654fade2f21f36b0313c",
  26. "title": "MongoDB 教程",
  27. "description": "MongoDB 是一个 Nosql 数据库",
  28. "by": "菜鸟教程",
  29. "url": "http://www.runoob.com",
  30. "tags": [
  31. "mongodb"
  32. ],
  33. "likes": 100
  34. }

2 MongoDB 操作符 - $type 实例

如果想获取 “col” 集合中 title 为 String 的数据,你可以使用以下命令:

  1. db.col.find({"title" : {$type : 2}})
  2. 或
  3. db.col.find({"title" : {$type : 'string'}})
  4. 输出结果为:
  5. {
  6. "_id": "56066542ade2f21f36b0313a",
  7. "title": "PHP 教程",
  8. "description": "PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。",
  9. "by": "菜鸟教程",
  10. "url": "http://www.runoob.com",
  11. "tags": [
  12. "php"
  13. ],
  14. "likes": 200
  15. }
  16. {
  17. "_id": "56066549ade2f21f36b0313b",
  18. "title": "Java 教程",
  19. "description": "Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。",
  20. "by": "菜鸟教程",
  21. "url": "http://www.runoob.com",
  22. "tags": [
  23. "java"
  24. ],
  25. "likes": 150
  26. }
  27. {
  28. "_id": "5606654fade2f21f36b0313c",
  29. "title": "MongoDB 教程",
  30. "description": "MongoDB 是一个 Nosql 数据库",
  31. "by": "菜鸟教程",
  32. "url": "http://www.runoob.com",
  33. "tags": [
  34. "mongodb"
  35. ],
  36. "likes": 100
  37. }