MongoDB简介

    MongoDB将数据存储为一个文档,一个文档由一系列的“键值对”组成,其文档类似于JSON对象,但是MongoDB对JSON进行了二进制处理(能够更快的定位key和value),因此其文档的存储格式称为BSON。关于JSON和BSON的差别大家可以看看MongoDB官方网站的文章《JSON and BSON》

    目前,MongoDB已经提供了对Windows、macOS、Linux、Solaris等多个平台的支持,而且也提供了多种开发语言的驱动程序,Python当然是其中之一。

    MongoDB的安装和启动

    可以从MongoDB的官方下载链接下载MongoDB,官方提供了Windows、macOS和多种Linux版本的安装包。下面以CentOS为例,简单说一下如何安装和启动MongoDB。

    下载服务器和命令行的RPM安装包。

    启动MongoDB服务器,需要先创建保存数据的文件夹。

    1. vim /etc/mongod.conf

    使用systemctl命令启动服务。

    MongoDB基本概念

    我们通过与关系型数据库的比较来说明MongoDB中的一些概念。

    通过Shell操作MongoDB

    1. 启动命令行工具,进入交互式环境。

      1. mongo
    2. 查看、创建和删除数据库。

      1. > // 显示所有数据库
      2. > show dbs
      3. admin 0.000GB
      4. config 0.000GB
      5. local 0.000GB
      6. > // 创建并切换到school数据库
      7. > use school
      8. switched to db school
      9. > // 删除当前数据库
      10. > db.dropDatabase()
      11. { "ok" : 1 }
    3. 说明:在MongoDB中插入文档时如果集合不存在会自动创建集合,所以也可以按照下面的方式通过插入文档来创建集合。

    4. 文档的CRUD操作。

      1. > // 向students集合插入文档
      2. > db.students.insert({stuid: 1001, name: '骆昊', age: 40})
      3. WriteResult({ "nInserted" : 1 })
      4. > // 向students集合插入文档
      5. > db.students.save({stuid: 1002, name: '王大锤', tel: '13012345678', gender: '男'})
      6. WriteResult({ "nInserted" : 1 })
      7. > // 查看所有文档
      8. > db.students.find()
      9. { "_id" : ObjectId("5b13c72e006ad854460ee70b"), "stuid" : 1001, "name" : "骆昊", "age" : 38 }
      10. { "_id" : ObjectId("5b13c790006ad854460ee70c"), "stuid" : 1002, "name" : "王大锤", "tel" : "13012345678", "gender" : "男" }
      11. > // 更新stuid为1001的文档
      12. > db.students.update({stuid: 1001}, {'$set': {tel: '13566778899', gender: '男'}})
      13. WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
      14. > // 插入或更新stuid为1003的文档
      15. WriteResult({
      16. "nMatched" : 0,
      17. "nUpserted" : 1,
      18. "nModified" : 0,
      19. "_id" : ObjectId("5b13c92dd185894d7283efab")
      20. > // 查询所有文档
      21. > db.students.find().pretty()
      22. {
      23. "_id" : ObjectId("5b13c72e006ad854460ee70b"),
      24. "stuid" : 1001,
      25. "name" : "骆昊",
      26. "age" : 38,
      27. "gender" : "男",
      28. "tel" : "13566778899"
      29. }
      30. {
      31. "_id" : ObjectId("5b13c790006ad854460ee70c"),
      32. "stuid" : 1002,
      33. "name" : "王大锤",
      34. "tel" : "13012345678",
      35. "gender" : "男"
      36. }
      37. {
      38. "_id" : ObjectId("5b13c92dd185894d7283efab"),
      39. "stuid" : 1003,
      40. "gender" : "男",
      41. "name" : "白元芳",
      42. "tel" : "13022223333"
      43. }
      44. > // 查询stuid大于1001的文档
      45. > db.students.find({stuid: {'$gt': 1001}}).pretty()
      46. {
      47. "_id" : ObjectId("5b13c790006ad854460ee70c"),
      48. "stuid" : 1002,
      49. "name" : "王大锤",
      50. "tel" : "13012345678",
      51. }
      52. {
      53. "_id" : ObjectId("5b13c92dd185894d7283efab"),
      54. "stuid" : 1003,
      55. "gender" : "男",
      56. "tel" : "13022223333"
      57. }
      58. > // 查询stuid大于1001的文档只显示name和tel字段
      59. > db.students.find({stuid: {'$gt': 1001}}, {_id: 0, name: 1, tel: 1}).pretty()
      60. { "name" : "王大锤", "tel" : "13012345678" }
      61. { "name" : "白元芳", "tel" : "13022223333" }
      62. > // 查询name为“骆昊”或者tel为“13022223333”的文档
      63. > db.students.find({'$or': [{name: '骆昊'}, {tel: '13022223333'}]}, {_id: 0, name: 1, tel: 1}).pretty()
      64. { "name" : "骆昊", "tel" : "13566778899" }
      65. { "name" : "白元芳", "tel" : "13022223333" }
      66. > // 查询学生文档跳过第1条文档只查1条文档
      67. > db.students.find().skip(1).limit(1).pretty()
      68. {
      69. "_id" : ObjectId("5b13c790006ad854460ee70c"),
      70. "stuid" : 1002,
      71. "name" : "王大锤",
      72. "tel" : "13012345678",
      73. "gender" : "男"
      74. }
      75. > // 对查询结果进行排序(1表示升序,-1表示降序)
      76. > db.students.find({}, {_id: 0, stuid: 1, name: 1}).sort({stuid: -1})
      77. { "stuid" : 1003, "name" : "白元芳" }
      78. { "stuid" : 1002, "name" : "王大锤" }
      79. { "stuid" : 1001, "name" : "骆昊" }
      80. > // 在指定的一个或多个字段上创建索引
      81. > db.students.ensureIndex({name: 1})
      82. {
      83. "createdCollectionAutomatically" : false,
      84. "numIndexesBefore" : 1,
      85. "numIndexesAfter" : 2,
      86. "ok" : 1

    使用MongoDB可以非常方便的配置数据复制,通过冗余数据来实现数据的高可用以及灾难恢复,也可以通过数据分片来应对数据量迅速增长的需求。关于MongoDB更多的操作可以查阅 ,同时推荐大家阅读Kristina Chodorow写的《MongoDB权威指南》

    在Python程序中操作MongoDB

    可以通过pip安装pymongo来实现对MongoDB的操作。

    1. pip install pymongo

    进入Python交互式环境,就可以执行以下的操作。