一、Mongodb简介  官网地址:http://www.mongodb.org/

  1. MongoDB是一个高性能,开源,无模式的文档型数据库,是当前NoSql数据库中比较热门的一种。MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能
  2. 最丰富,最像关系数据库的。它在许多场景下可用于替代传统的关系型数据库或键/值存储方式。它是由C++语言编写的一个基于分布式文件存储的开源数据库系统,它的目的在于为WEB
  3. 用提供可扩展的高性能数据存储解决方案。MongoDB是一个介于关系型数据库和非关系型数据库之间的产品,是非关系型数据库当中功能最丰富,最像关系型数据库的。它支持的数据结构
  4. 非常松散,会将数据存储为一个文档,数据结构由键值对(key=>value)组成,是类似于jsonbson格式,字段值可以包含其它文档、数组和文档数组,因此可以存储比较复杂的数据类型。

二、Mongodb特点

  1. MongoDB特点是高性能、易部署、易使用,存储数据非常方便,最大的特点在于它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系型数据库单表
  2. 查询的绝大部分功能,而且还支持对数据建立索引。MongoDB的主要特点总结如下:
  3. 1)提供了一个面向集合的文档存储,易存储对象类型的数据,操作起来比较简单和容易的非关系型数据库
  4. 2)使用update()命令可以实现替换完成的文档(数据)或者一些指定的数据字段。
  5. 3)支持动态查询。
  6. 4)支持完全索引,包含内部对象,可以在MongoDB记录中设置任何属性的索引来实现更快的排序。
  7. 5)支持复制和故障恢复。
  8. 6)使用高效的二进制数据存储,包括大型对象(如视频等)。
  9. 7GridFSMongoDB中的一个内置功能,可以用于存放大量小文件。
  10. 8)自动处理碎片,以支持云计算层次的扩展性;如果负载的增加(需要更多的存储空间和更强的处理能力),它可以分布在计算机网络中的其它节点上,这就是所谓的分片。
  11. 9)支持RUBYPYTHONJAVAC++,PHPC#等多种语言。
  12. 10)文件存储格式为BSON(一种JSON的扩展),MongoDB支持丰富的查询表达式,查询指令使用JSON形式的标记,可轻易查询文档中内嵌的对象和数组。
  13. 11MongoDB允许在服务端执行脚本,可以用JavaScript编写某个函数,直接在服务端执行,也可以吧函数的定义存储在服务端,下次直接调用即可。
  14. 12)可通过网络访问,可以通过本地u或者网络创建数据镜像,这使得MongoDB含有更强的扩展性。

Mongodb的不足之处

  1. 1)在集群分片中的数据分布不均匀
  2. 2)单机可靠性比较差
  3. 3)大数据量持续插入,写入性能有较大波动
  4. 4)不支持事务操作。所以事务要求严格的系统(如果银行系统)肯定不能用它。
  5. 5)磁盘空间占用比较大。空间占用大的原因如下:
  6. 1-> 空间的预分配:为避免形成过多的硬盘碎片,mongodb 每次空间不足时都会申请生成一大块的硬盘空 间,而且申请的量从 64M128M256M 那样的指数递增,直到2G为单个文件
  7. 的最大体积。随着数据量 的增加,你可以在其数据目录里看到这些整块生成容量不断递增的文件。
  8. 2-> 字段名所占用的空间:为了保持每个记录内的结构信息用于查询,mongodb 需要把每个字段的 key-value 都以 BSON 的形式存储,如果 value 域相对于 key 域并不大,比如
  9. 存放数值型的数据,则数据的 overhead 是最大的。一种减少空间占用的方法是把字段名尽量取短一些,这样占用 空间就小了,但这就要求在易读 性与空间占用上作为权衡了。
  10. 3-> 删除记录不释放空间:这很容易理解,为避免记录删除后的数据的大规模挪动,原记录空间不删除,只 标记“已删除”即可,以后还可以重复利用。
  11. 4-> 可以定期运行 db.repairDatabase()来整理记录,但这个过程会比较缓慢

三、Mongodb功能

  1. 1)面向集合的存储:适合存储对象及JSON形式的数据。
  2. 2)动态查询:Mongo支持丰富的查询表达式。查询指令使用JSON形式的标记,可轻易查询文档中内嵌的对象及数组。
  3. 3)完整的索引支持:包括文档内嵌对象及数组。Mongo的查询优化器会分析查询表达式,并生成一个高效的查询计划。
  4. 4)查询监视:Mongo包含一个监视工具用于分析数据库操作的性能。
  5. 5)复制及自动故障转移:Mongo数据库支持服务器之间的数据复制,支持主-从模式及服务器之间的相互复制。复制的主要目标是提供冗余及自动故障转移。
  6. 6)高效的传统存储方式:支持二进制数据及大型对象(如照片或图片)
  7. 7)自动分片以支持云级别的伸缩性:自动分片功能支持水平的数据库集群,可动态添加额外的机器。

四、Mongodb使用场景

  1. 适用场景:
  2. 网站实时数据处理。它非常适合实时的插入、更新与查询,并具备网站实时数据存储所需的复制及高度伸缩性;缓存,由于性能很高,它适合作为信息基础设施的缓存层。在系统重启之后,
  3. 由它搭建的持久化缓存层可以避免下层的数据源过载。高伸缩性的场景。非常适合由数十或数百台服务器组成的数据库,它的路线图中已经包含对MapReduce引擎的内置支持。
  4.  
  5. 不适用场景:
  6. 要求高度事务性的系统。传统的商业智能应用。复杂的跨文档(表)级联查询。

五、Mongodb安装使用  官网下载地址:http://www.mongodb.org/downloads

  1. 1)安装mongodb
  2. [root@data-server src]# cd /usr/local/src/
  3. [root@data-server src]# tar -zvxf mongodb-linux-x86_64-rhel62-3.4.4
  4. [root@data-server src]# mv mongodb-linux-x86_64-rhel62-3.4.4 /usr/local/mongodb
  5. [root@data-server src]# cd /usr/local/mongodb //Mongodb主目录
  6. [root@data-server mongodb]# ll
  7. 总用量 120
  8. drwxr-xr-x. 2 root root 4096 6 3 14:51 bin
  9. -rw-r--r--. 1 root root 34520 4 21 06:19 GNU-AGPL-3.0
  10. -rw-r--r--. 1 root root 16726 4 21 06:19 MPL-2
  11. -rw-r--r--. 1 root root 1359 4 21 06:19 README
  12. -rw-r--r--. 1 root root 55625 4 21 06:19 THIRD-PARTY-NOTICES
  13. [root@data-server mongodb]# mkdir /usr/local/mongodb/data //Mongodb数据目录,可以存放在一个独立的大分区上
  14. [root@data-server mongodb]# mkdir /usr/local/mongodb/log //Mongodb日志目录
  15.  
  16. 2)启动Mongodb
  17. 使用mongod命令建立一个mongodb数据库链接,端口号设置为10001,数据库的路径为/usr/local/mongodb/data,日志路径为/usr/local/mongodb/log/mongo.log
  18. mongodb的启动程序放在后台执行,下面命令执行后,按ctrlc
  19. [root@data-server mongodb]# nohup /usr/local/mongodb/bin/mongod --dbpath=/usr/local/mongodb/data/ --logpath=/usr/local/mongodb/log/mongo.log &
  20.  
  21. mongodb默认端口是27017
  22. [root@data-server mongodb]# ps -ef|grep mongodb
  23. root 14858 14518 1 15:01 pts/1 00:00:01 /usr/local/mongodb/bin/mongod --dbpath=/usr/local/mongodb/data/ --logpath=/usr/local/mongodb/log/mongo.log
  24. root 14887 14518 0 15:02 pts/1 00:00:00 grep mongodb
  25. [root@data-server bin]# netstat -tunlp|grep 14858
  26. tcp 0 0 0.0.0.0:27017 0.0.0.0:* LISTEN 14858/mongod
  27. [root@data-server mongodb]# lsof -i:27017
  28. COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
  29. mongod 14858 root 7u IPv4 145311 0t0 TCP *:27017 (LISTEN)
  30.  
  31. 3)设置mongodb的环境变量
  32. [root@data-server ~]# vim /etc/profile
  33. .......
  34. export PATH=$PATH:/usr/local/mongodb/bin/
  35. [root@data-server ~]# source /etc/profile
  36.  
  37. 4)为了更方便的启动和关闭MongoDB,我们可以使用Shell写脚本,当然也可以加入到service
  38. 更好的方式是采用配置文件,把MongoDB需要的参数写入配置文件,然后在脚本中引用;
  39. [root@data-server ~]# cat /usr/local/mongodb/mongodb.conf
  40. #代表端口号,如果不指定则默认为27017
  41. port=27017
  42. #MongoDB数据文件目录
  43. dbpath=/usr/local/mongodb/data
  44. #MongoDB日志文件目录
  45. logpath=/usr/local/mongodb/log/mongo.log
  46. #日志文件自动累加
  47. logappend=true
  48.  
  49. 编写启动脚本
  50. [root@data-server ~]# vim /etc/init.d/mongodb
  51. #!/bin/bash
  52. #
  53. # mongod Start up the MongoDB server daemon
  54. #
  55.  
  56. # source function library
  57. . /etc/rc.d/init.d/functions
  58. #定义命令
  59. CMD=/usr/local/mongodb/bin/mongod
  60. #定义配置文件路径
  61. INITFILE=/usr/local/mongodb/mongodb.conf
  62. start()
  63. {
  64. #&表示后台启动,也可以使用fork参数
  65. $CMD -f $INITFILE &
  66. echo "MongoDB is running background..."
  67. }
  68.  
  69. stop()
  70. {
  71. pkill mongod
  72. echo "MongoDB is stopped."
  73. }
  74.  
  75. case "$1" in
  76. start)
  77. start
  78. ;;
  79. stop)
  80. stop
  81. ;;
  82. *)
  83. echo $"Usage: $0 {start|stop}"
  84. esac
  85. [root@data-server ~]# chmod 755 /etc/init.d/mongodb
  86. [root@data-server ~]# /etc/init.d/mongodb status
  87. 用法:/etc/init.d/mongodb {start|stop}
  88. [root@data-server ~]# /etc/init.d/mongodb stop
  89. 已终止
  90. [root@data-server ~]# lsof -i:27017
  91. [root@data-server ~]# /etc/init.d/mongodb start
  92. MongoDB is running background...
  93. [root@data-server ~]# lsof -i:27017
  94. COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
  95. mongod 15138 root 7u IPv4 147713 0t0 TCP *:27017 (LISTEN)
  96.  
  97. 通过 shell 连接 MongoDB 服务:(在客户机上连接本机mongodbmongo 182.48.115.238:27017)
  98. [root@data-server ~]# mongo
  99. MongoDB shell version v3.4.4
  100. connecting to: mongodb://127.0.0.1:27017
  101. MongoDB server version: 3.4.4
  102. Welcome to the MongoDB shell.
  103. For interactive help, type "help".
  104. For more comprehensive documentation, see
  105. http://docs.mongodb.org/
  106. Questions? Try the support group
  107. http://groups.google.com/group/mongodb-user
  108. Server has startup warnings:
  109. 2017-06-03T15:17:54.695+0800 I STORAGE [initandlisten]
  110. 2017-06-03T15:17:54.695+0800 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
  111. 2017-06-03T15:17:54.695+0800 I STORAGE [initandlisten] ** See http://dochub.mongodb.org/core/prodnotes-filesystem
  112. 2017-06-03T15:17:55.699+0800 I CONTROL [initandlisten]
  113. 2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
  114. 2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
  115. 2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
  116. 2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten]
  117. 2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten]
  118. 2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
  119. 2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never'
  120. 2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten]
  121. 2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
  122. 2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never'
  123. 2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten]
  124. > help
  125. db.help() help on db methods
  126. db.mycoll.help() help on collection methods
  127. sh.help() sharding helpers
  128. rs.help() replica set helpers
  129. help admin administrative help
  130. help connect connecting to a db help
  131. help keys key shortcuts
  132. help misc misc things to know
  133. help mr mapreduce
  134.  
  135. show dbs show database names
  136. show collections show collections in current database
  137. show users show users in current database
  138. show profile show most recent system.profile entries with time >= 1ms
  139. show logs show the accessible logger names
  140. show log [name] prints out the last segment of log in memory, 'global' is default
  141. use <db_name> set current database
  142. db.foo.find() list objects in collection foo
  143. db.foo.find( { a : 1 } ) list objects in foo where a == 1
  144. it result of the last line evaluated; use to further iterate
  145. DBQuery.shellBatchSize = x set default number of items to display on shell
  146. exit quit the mongo shell

mongodb非正常关闭导致启动失败问题

之前强制关闭了mongodb,后续再次启动的时候,发现报错:
[root@i-omxpbsuo ~]# /usr/local/mongodb/bin/mongod --logpath /usr/local/mongodb/log/system.log --logappend --dbpath /data/mongodb --directoryperdb --auth --journal --profile=1 --slowms=5 --fork 
forked process: 4853
all output going to: /usr/local/mongodb/log/system.log

查看日志

这是由于上次mongodb非正常关闭导致的。
解决办法:
1)删除数据目录/data/mongodb 下的 mongod.lock 
[root@i-omxpbsuo ~]# rm -rf /data/mongodb/mongod.lock

2)修复mongodb
[root@i-omxpbsuo ~]# /usr/local/mongodb/bin/mongod --logpath --dbpath /data/mongodb --repair

3)删除/data/mongodb/journal 下的 j._4 文件(或者将journal下的文件清空)
[root@i-omxpbsuo ~]# rm -rf /data/mongodb/journal/*j._4

4)然后再次启动mongodb就ok了
[root@i-omxpbsuo ~]# /usr/local/mongodb/bin/mongod --logpath --dbpath /data/mongodb --directoryperdb --auth --journal --profile=1 --slowms=5 --fork &

  1. ========================================================
  2. 正确关闭mongod 的方法:进入mongo shell
  3. > use admin
  4. > db.shutdownServer()
  5.  
  6. 也可以按照文档粗暴的杀掉它,它内部应该有KILL信号处理程序。
  7. # killall mongod
  8.  
  9. 请不要 kill -9 ,会造成文件数据混乱丢失repair也无力回天。
  10. =======================================================

除此之外,还可以采用yum的方式安装mongodb,操作记录如下:

  1. 1)创建repo
  2. [root@data-server ~]# vim /etc/yum.repos.d/mongodb-org-3.2.repo
  3. [mongodb-org-3.2]
  4. name=MongoDB Repository
  5. baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/
  6. gpgcheck=0
  7. enabled=1
  8.  
  9. 2)安装MongoDB和相关工具
  10. [root@data-server ~]# yum install -y mongodb-org
  11.  
  12. 3)启动Mongodb
  13. [root@data-server ~]# service mongod start
  14. Starting mongod: [ OK ]
  15. [root@data-server ~]# chkconfig mongod on
  16. [root@data-server ~]# lsof -i:27017
  17. COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
  18. mongod 26130 mongod 6u IPv4 2773161 0t0 TCP localhost:27017 (LISTEN)
  19.  
  20. 日志文件:/var/log/mongodb/mongod.log
  21. 配置文件:/etc/mongod.conf
  22. 数据目录:/var/lib/mongo/
  23.  
  24. 配置文件解释:
  25. [root@data-server ~]# cat /etc/mongod.conf
  26. # mongo.conf
  27.  
  28. #where to log
  29. logpath=/var/log/mongo/mongod.log
  30.  
  31. logappend=true #以追加方式写入日志
  32.  
  33. # fork and run in background
  34. fork = true
  35.  
  36. #port = 27017 #端口
  37.  
  38. dbpath=/var/lib/mongo #数据库文件保存位置
  39. directoryperdb=true
  40. # Enables periodic logging of CPU utilization and I/O wait
  41. #启用定期记录CPU利用率和 I/O 等待
  42. #cpu = true
  43.  
  44. # Turn on/off security. Off is currently the default
  45. # 是否以安全认证方式运行,默认是不认证的非安全方式
  46. #noauth = true
  47. #auth = true
  48.  
  49. # Verbose logging output.
  50. # 详细记录输出
  51. #verbose = true
  52.  
  53. # Inspect all client data for validity on receipt (useful for
  54. # developing drivers)用于开发驱动程序时的检查客户端接收数据的有效性
  55. #objcheck = true
  56.  
  57. # Enable db quota management 启用数据库配额管理,默认每个db可以有8个文件,可以用quotaFiles参数设置
  58. #quota = true
  59. # 设置oplog记录等级
  60. # Set oplogging level where n is
  61. # 0=off (default)
  62. # 1=W
  63. # 2=R
  64. # 3=both
  65. # 7=W+some reads
  66. #oplog = 0
  67.  
  68. # Diagnostic/debugging option 动态调试项
  69. #nocursors = true
  70.  
  71. # Ignore query hints 忽略查询提示
  72. #nohints = true
  73. # 禁用http界面,默认为localhost:28017
  74. # Disable the HTTP interface (Defaults to localhost:27018).这个端口号写的是错的
  75. #nohttpinterface = true
  76.  
  77. # 关闭服务器端脚本,这将极大的限制功能
  78. # Turns off server-side scripting. This will result in greatly limited
  79. # functionality
  80. #noscripting = true
  81. # 关闭扫描表,任何查询将会是扫描失败
  82. # Turns off table scans. Any query that would do a table scan fails.
  83. #notablescan = true
  84. # 关闭数据文件预分配
  85. # Disable data file preallocation.
  86. #noprealloc = true
  87. # 为新数据库指定.ns文件的大小,单位:MB
  88. # Specify .ns file size for new databases.
  89. # nssize = <size>
  90.  
  91. # Accout token for Mongo monitoring server.
  92. #mms-token = <token>
  93. # mongo监控服务器的名称
  94. # Server name for Mongo monitoring server.
  95. #mms-name = <server-name>
  96. # mongo监控服务器的ping 间隔
  97. # Ping interval for Mongo monitoring server.
  98. #mms-interval = <seconds>
  99.  
  100. # Replication Options 复制选项
  101.  
  102. # in replicated mongo databases, specify here whether this is a slave or master 在复制中,指定当前是从属关系
  103. #slave = true
  104. #source = master.example.com
  105. # Slave only: specify a single database to replicate
  106. #only = master.example.com
  107. # or
  108. #master = true
  109. #source = slave.example.com

 六、Mongodb的日常操作命令

  1. 1)登陆和退出..........................................
  2. mongo 命令直接加MongoDB服务器的IP地址就可以利用 Mongo 的默认端口号(27017)登陆 Mongo,然后便能够进行简单的命令行操作。至于退出,直接 exit,然后回车就好了。
  3.  
  4. 如果默认bind绑定的ip127.0.0.1以及端口是27017,那么登陆可以直接用下面两种都可以:
  5. [root@master-node ~]# mongo
  6. [root@master-node ~]# mongo 127.0.0.1:27017
  7.  
  8. 如果是绑定了固定的ip地址,如bind_ip=182.48.115.236,那么连接mongodb命令是:
  9. [root@master-node ~]# mongo 182.48.115.238:27017
  10.  
  11. 如果是连接某个库,命令是
  12. [root@master-node ~]# mongo ip:port/库名 -u用户名 -p密码
  13.  
  14. > help
  15. 登陆mongodb数据库后,可以直接执行help命令进行帮助查看
  16.  
  17. > show collections
  18. 从以上可以看出,登录后 mongo 会自动连上一个名为 test 的数据库。如果这个数据库不存 在,那么 mongo 会自动建立一个名为 test 的数据库。上面的例子,由于 Mongo 服务器上没 有名为 test db,因此,mongo 新建了一个空的名为 test db。其中,没有任何 collection
  19.  
  20. 2database级操作..........................................
  21.  
  22. 2.1 查看服务器上的数据库
  23. > show dbs
  24. admin 0.000GB
  25. local 0.000GB
  26. master_slave 0.000GB
  27. wangshibo 0.000GB
  28.  
  29. 2.2 切换数据库
  30. 切换到wangshibo数据库(从默认的 test 数据库)
  31. > use wangshibo
  32. switched to db wangshibo
  33. mongo 中,db 代表当前使用的数据库。这样,db 就从原来的 test,变为现在的 wangshibo 数据库,如果没有这个库,就会自动创建
  34.  
  35. 2.3 查看当前数据库中的所有集合
  36. > show collections
  37. persons
  38. test
  39.  
  40. 2.4 创建数据库
  41. mongo 中创建数据库采用的也是 use 命令,如果 use 后面跟的数据库名不存在,那么 mongo 将会新建该数据库。
  42. 不过,实际上只执行 use 命令后,mongo 是不会新建该数据库的,直到 你像该数据库中插入了数据。
  43. > use huanqiu
  44. switched to db huanqiu
  45. > show dbs
  46. admin 0.000GB
  47. local 0.000GB
  48. master_slave 0.000GB
  49. wangshibo 0.000GB
  50. 到这里并没有看到刚才新建的 huanqiu 数据库。
  51.  
  52. > db.huanqiu.insert({"name":"testdb"})
  53. WriteResult({ "nInserted" : 1 })
  54. 该操作会在 huanqiu 数据库中新建一个 hello 集合,并在其中插入一条记录。
  55.  
  56. > show dbs
  57. admin 0.000GB
  58. huanqiu 0.000GB
  59. local 0.000GB
  60. master_slave 0.000GB
  61. wangshibo 0.000GB
  62. 这样,便可以看到 mongo 的确创建了 huanqiu 数据库,其中有一个 hello 集合。
  63.  
  64. 2.5 删除数据库
  65. 删除当前所在库。比如这里已经切换到huanqiu库,那么就删除huanku
  66. > db.dropDatabase()
  67. { "dropped" : "huanqiu", "ok" : 1 }
  68.  
  69. > show dbs
  70. admin 0.000GB
  71. local 0.000GB
  72. master_slave 0.000GB
  73. wangshibo 0.000GB
  74.  
  75. 2.6 查看当前数据库
  76. > db
  77. huanqiu
  78.  
  79. > db.getName(); //这个上面的命令是一样的
  80. wangshibo
  81.  
  82. 可以看出删除 huanqiu 数据库之后,当前的 db 还是指向它,只有当切换数据库之后,huanqiu 才会彻底消失。
  83. > use wangshibo
  84. switched to db wangshibo
  85. > db
  86. wangshibo
  87. > show dbs
  88. admin 0.000GB
  89. local 0.000GB
  90. master_slave 0.000GB
  91. wangshibo 0.000GB
  92.  
  93. 2.6.1 修复当前数据库
  94. > db.repairDatabase();
  95. { "ok" : 1 }
  96.  
  97. 2.6.2 查看当前数据库状态
  98. > db.stats();
  99. {
  100. "db" : "wangshibo",
  101. "collections" : 3,
  102. "views" : 0,
  103. "objects" : 6,
  104. "avgObjSize" : 75.5,
  105. "dataSize" : 453,
  106. "storageSize" : 73728,
  107. "numExtents" : 0,
  108. "indexes" : 4,
  109. "indexSize" : 53248,
  110. "ok" : 1
  111. }
  112.  
  113. 2.6.3 当前db版本
  114. > db.version();
  115. 3.4.4
  116.  
  117. 2.6.4 查看当前db的链接机器地址
  118. > db.getMongo();
  119. connection to 182.48.115.238:27017
  120.  
  121. 2.6.5 从指定主机上克隆数据库
  122. > db.cloneDatabase("182.48.115.236");
  123. {
  124. "clonedColls" : [ ],
  125. "ok" : 0,
  126. "errmsg" : "a collection 'wangshibo.wangshibo' already exists",
  127. "code" : 48,
  128. "codeName" : "NamespaceExists"
  129. }
  130.  
  131. 2.6.6 从指定的机器上复制指定数据库数据到某个数据库
  132. 将本机的master_slave的数据复制到wangshibo数据库中
  133. > db.copyDatabase("master_slave", "wangshibo", "127.0.0.1");
  134. { "ok" : 1 }
  135.  
  136. 3collection 级操作..........................................
  137.  
  138. 3.1 新建 collection
  139. > db.createCollection("Hello")
  140. { "ok" : 1 }
  141. > show collections
  142. Hello
  143. wangshibo
  144.  
  145. 直接向一个不存在的 collection 中插入数据也能创建一个 collection
  146. > db.hello2.insert({"name":"lfqy"})
  147. WriteResult({ "nInserted" : 1 })
  148. > show collections
  149. Hello
  150. hello2
  151. wangshibo
  152.  
  153. 3.2 删除 collection
  154. > db.Hello.drop()
  155. true
  156. 返回 true 说明删除成功,false 说明没有删除成功。
  157.  
  158. > db.Hello.drop()
  159. false
  160. 不存在名为 hello collection,因此,删除失败。
  161.  
  162. 3.3 重命名 collection
  163. hello2 集合重命名为 HELLO
  164. > show collections
  165. hello2
  166. wangshibo
  167. > db.hello2.renameCollection("HELLO")
  168. { "ok" : 1 }
  169. > show collections
  170. HELLO
  171. wangshibo
  172.  
  173. 3.4 查看当前数据库中的所有 collection
  174. > show collections
  175. HELLO
  176. wangshibo
  177.  
  178. 3.5 建立索引在 HELLO 集合上,建立对 ID 字段的索引,1 代表升序。
  179. > db.HELLO.ensureIndex({ID:1})
  180. {
  181. "createdCollectionAutomatically" : false,
  182. "numIndexesBefore" : 1,
  183. "numIndexesAfter" : 2,
  184. "ok" : 1
  185. }
  186.  
  187. 4Record 级的操作................................
  188.  
  189. 4.1 插入操作
  190. 4.1.1 user 集合中插入两条记录
  191. > db.user.insert({'name':'GalGadot','gender':'female','age':28,'salary':11000})
  192. WriteResult({ "nInserted" : 1 })
  193. > db.user.insert({'name':'Mikie Hara','gender':'female','age':26,'salary':7000})
  194. WriteResult({ "nInserted" : 1 })
  195.  
  196. 4.1.2 同样也可以用 save 完成类似的插入操作
  197. > db.user.save({'name':'Wentworth Earl Miller','gender':'male','age':41,'salary':33000})
  198. WriteResult({ "nInserted" : 1 })
  199.  
  200. 4.2 查找操作
  201. 4.2.1 查找集合中的所有记录
  202. > db.user.find()
  203. { "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
  204. { "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
  205. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  206.  
  207. 4.2.2 查找集合中的符合条件的记录
  208. (1)单一条件
  209. 查询 age 26 的数据
  210. > db.user.find({"age":26})
  211. { "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
  212.  
  213. 查询 salary 大于 7000 的数据
  214. > db.user.find({salary:{$gt:7000}})
  215. { "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
  216. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  217.  
  218. 查询 name 中包含'ent'的数据
  219. > db.user.find({name:/ent/})
  220. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  221.  
  222. 查询 name G 打头的数据
  223. > db.user.find({name:/^G/})
  224. { "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
  225.  
  226. 查询 name t 结尾的数据
  227. > db.user.find({name:/t$/})
  228. { "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
  229.  
  230. (2)多条件"与"
  231. 查询 age 小于 30,salary 大于 7000 的数据
  232. > db.user.find({age:{$lt:30},salary:{$gt:7000}})
  233. { "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
  234.  
  235. (3)多条件"或"
  236. 查询 age 小于 30,或者 salary 大于 10000 的记录
  237. > db.user.find({$or:[{salary:{$gt:10000}},{age:{$lt:30}}]})
  238. { "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
  239. { "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
  240. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  241.  
  242. 4.2.3 查询第一条记录
  243. 将上面的 find 替换为 findOne()可以查找符合条件的第一条记录。
  244. > db.user.findOne({$or:[{salary:{$gt:10000}},{age:{$lt:25}}]})
  245. {
  246. "_id" : ObjectId("59328c8aa7865327915046ae"),
  247. "name" : "GalGadot",
  248. "gender" : "female",
  249. "age" : 28,
  250. "salary" : 11000
  251. }
  252.  
  253. 4.2.4 查询记录的指定字段
  254. 查询 user 集合中所有记录的 name,age,salary,sex_orientation 字段
  255. > db.user.find({},{name:1,age:1,salary:1,sex_orientation:true})
  256. { "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "age" : 28, "salary" : 11000 }
  257. { "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "age" : 26, "salary" : 7000 }
  258. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "age" : 41, "salary" : 33000 }
  259.  
  260. 注意:这里的 1 表示显示此列的意思,也可以用 true 表示。
  261. > db.user.find({},{name:1,age:1,salary:true,sex_orientation:1})
  262. { "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "age" : 28, "salary" : 11000 }
  263. { "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "age" : 26, "salary" : 7000 }
  264. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "age" : 41, "salary" : 33000 }
  265.  
  266. 4.2.5 查询指定字段的数据,并去重。
  267. 查询 gender 字段的数据,并去掉重复数据
  268. > db.user.distinct('gender')
  269. [ "female", "male" ]
  270.  
  271. 4.2.6 对查询结果集的操作
  272. (1)Pretty Print
  273. 为了方便,mongo 也提供了 pretty print 工具,db.collection.pretty()或者是 db.collection.forEach(printjson)
  274. > db.user.find().pretty()
  275. {
  276. "_id" : ObjectId("59328c8aa7865327915046ae"),
  277. "name" : "GalGadot",
  278. "gender" : "female",
  279. "age" : 28,
  280. "salary" : 11000
  281. }
  282. {
  283. "_id" : ObjectId("59328c9da7865327915046af"),
  284. "name" : "Mikie Hara",
  285. "gender" : "female",
  286. "age" : 26,
  287. "salary" : 7000
  288. }
  289. {
  290. "_id" : ObjectId("59328cd6a7865327915046b0"),
  291. "name" : "Wentworth Earl Miller",
  292. "gender" : "male",
  293. "age" : 41,
  294. "salary" : 33000
  295. }
  296.  
  297. (2)指定结果集显示的条目
  298. a)显示结果集中的前 3 条记录
  299. > db.user.find().limit(3)
  300. { "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
  301. { "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
  302. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  303.  
  304. b)查询第 1 条以后的所有数据
  305. > db.user.find().skip(1)
  306. { "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
  307. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  308.  
  309. 查询跳过前2条以后的所有数据
  310. > db.user.find().skip(2)
  311. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  312. >
  313.  
  314. c)对结果集排序
  315. 升序
  316. > db.user.find().sort({salary:1})
  317. { "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
  318. { "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
  319. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  320.  
  321. 降序
  322. > db.user.find().sort({salary:-1})
  323. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  324. { "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
  325. { "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
  326.  
  327. 4.2.7 统计查询结果中记录的条数
  328. (1)统计集合中的所有记录条数
  329. > db.user.find().count()
  330. 3
  331.  
  332. (2)查询符合条件的记录数
  333. 查询 salary 小于 4000 或大于 10000 的记录数
  334. > db.user.find({$or: [{salary: {$lt:4000}}, {salary: {$gt:10000}}]}).count()
  335. 2
  336.  
  337. 4.3 删除操作
  338. 4.3.1 删除整个集合中的所有数据
  339.  
  340. > db.wangshibo.find()
  341. { "_id" : ObjectId("5932683b156e298477cdf3ad"), "name" : "菜鸟教程" }
  342. > db.wangshibo.remove({})
  343. WriteResult({ "nRemoved" : 1 })
  344. > db.wangshibo.find()
  345. >
  346. 可见 wangshibo中的记录全部被删除。
  347.  
  348. mongo在删除数据的时候不支持 all * 全部删除选择{}就可以全部删除了
  349. 删除mongodb集合中的数据可以使用remove()函数。remove()函数可以接受一个查询文档作为可选参数来有选择性的删除符合条件的文档。
  350. remove()函数不会删除集合本身,同时,原有的索引也同样不会被删除。
  351. 删除文档是永久性的,不能撤销,也不能恢复的。因此,在执行remove()函数前先用find()命令来查看下是否正确,是个比较好的习惯啦。
  352.  
  353. 注意 db.collection.remove()和 drop()的区别,remove()只是删除了集合中所有的记录, 而集合中原有的索引等信息还在,而
  354. drop()则把集合相关信息整个删除(包括索引)。
  355.  
  356. 4.3.2 删除集合中符合条件的所有记录
  357. > db.user.find()
  358. { "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
  359. { "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
  360. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  361. > db.user.remove({name:'GalGadot'})
  362. WriteResult({ "nRemoved" : 1 })
  363. > db.user.find()
  364. { "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
  365. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  366.  
  367. 4.3.3 删除集合中符合条件的一条记录
  368. > db.user.find()
  369. { "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
  370. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  371. > db.user.remove({salary :{$lt:30000}},1)
  372. WriteResult({ "nRemoved" : 1 })
  373. > db.user.find()
  374. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  375. >
  376.  
  377. 当然,也可以是命令:db.user.remove({salary :{$lt:30000}},true),因为true1是一个意思
  378.  
  379. 4.4 更新操作
  380. 4.4.1 赋值更新
  381. db.collection.update(criteria, objNew, upsert, multi )
  382. criteria:update 的查询条件,类似 sql update 查询内 where 后面的
  383. objNew:update 的对象和一些更新的操作符(如$,$inc...)等,也可以理解为 sql update 查询内 set 后面的。
  384. upsert : 如果不存在 update 的记录,是否插入 objNew,true 为插入,默认是 false,不插 入。
  385. multi : mongodb 默认是 false,只更新找到的第一条记录,如果这个参数为 true,就把按条 件查出来多条记录全部更新。
  386.  
  387. > db.user.find()
  388. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  389. { "_id" : ObjectId("593293e2a7865327915046b2"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
  390. { "_id" : ObjectId("593293f0a7865327915046b3"), "name" : "Gasdfdst", "gender" : "female", "age" : 58, "salary" : 60000 }
  391. { "_id" : ObjectId("59329401a7865327915046b4"), "name" : "huihui", "gender" : "female", "age" : 18, "salary" : 23100 }
  392. > db.user.update({name:'huihui'},{$set:{age:23}},false,true)
  393. WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
  394. > db.user.find()
  395. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  396. { "_id" : ObjectId("593293e2a7865327915046b2"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
  397. { "_id" : ObjectId("593293f0a7865327915046b3"), "name" : "Gasdfdst", "gender" : "female", "age" : 58, "salary" : 60000 }
  398. { "_id" : ObjectId("59329401a7865327915046b4"), "name" : "huihui", "gender" : "female", "age" : 23, "salary" : 23100 }
  399.  
  400. > db.user.update({name:'lfqy1'},{$set:{age:23}},true,true)
  401. WriteResult({
  402. "nMatched" : 0,
  403. "nUpserted" : 1,
  404. "nModified" : 0,
  405. "_id" : ObjectId("5932946c9758703fe04b0f73")
  406. })
  407. > db.user.find()
  408. { "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  409. { "_id" : ObjectId("593293e2a7865327915046b2"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
  410. { "_id" : ObjectId("593293f0a7865327915046b3"), "name" : "Gasdfdst", "gender" : "female", "age" : 58, "salary" : 60000 }
  411. { "_id" : ObjectId("59329401a7865327915046b4"), "name" : "huihui", "gender" : "female", "age" : 23, "salary" : 23100 }
  412. { "_id" : ObjectId("5932946c9758703fe04b0f73"), "name" : "lfqy1", "age" : 23 }
  413.  
  414. 4.4.2 增值更新
  415. > db.user.find()
  416. { "_id" : ObjectId("52453cfb25e437dfea8fd4f4"), "name" : "Gal Gadot", "gender" : "female", "age" : 28, "salary" : 11000 }
  417. { "_id" : ObjectId("52453d8525e437dfea8fd4f5"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
  418. { "_id" : ObjectId("52453e2125e437dfea8fd4f6"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  419. { "_id" : ObjectId("52454155d8947fb70d000000"), "name" : "not known", "sex_orientation" : "male", "age" : 13, "salary" : 30000 }
  420. { "_id" : ObjectId("5245610881c83a5bf26fc285"), "age" : 23, "name" : "lfqy1" }
  421. { "_id" : ObjectId("52455f8925e437dfea8fd4fd"), "age" : 23, "gender" : "male", "interest" : "NBA", "name" : "lfqy", "salary" : 1 }
  422. { "_id" : ObjectId("5245607525e437dfea8fd4fe"), "age" : 23, "gender" : "male", "interest" : "NBA", "name" : "lfqy", "salary" : 2 }
  423.  
  424. > db.user.update({gender:'female'},{$inc:{salary:50}},false,true)
  425.  
  426. > db.user.find()
  427. { "_id" : ObjectId("52453cfb25e437dfea8fd4f4"), "name" : "Gal Gadot", "gender" : "female", "age" : 28, "salary" : 11050 }
  428. { "_id" : ObjectId("52453d8525e437dfea8fd4f5"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7050 }
  429. { "_id" : ObjectId("52453e2125e437dfea8fd4f6"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
  430. { "_id" : ObjectId("52454155d8947fb70d000000"), "name" : "not known", "sex_orientation" : "male", "age" : 13, "salary" : 30000 }
  431. { "_id" : ObjectId("5245610881c83a5bf26fc285"), "age" : 23, "name" : "lfqy1" }
  432. { "_id" : ObjectId("52455f8925e437dfea8fd4fd"), "age" : 23, "gender" : "male", "interest" : "NBA", "name" : "lfqy", "salary" : 1 }
  433. { "_id" : ObjectId("5245607525e437dfea8fd4fe"), "age" : 23, "gender" : "male", "interest" : "NBA", "name" : "lfqy", "salary" : 2 }
  434. 关于更新操作(db.collection.update(criteria, objNew, upsert, multi )),要说明的 是,如果 upsert true,那么在没有找到符合更新条件的情况下,mongo 会在集合中插入 一条记录其值满足更新条件的记录(其中的字段只有更新条件中涉及的字段,字段的值满足 更新条件),然后将其更新(注意,如果更新条件是$lt 这种不等式条件,那么 upsert 插入
  435.  
  436. --------------------------------------------------------------------------------------
  437. 其它命令操作:
  438. 1、创建一个聚集集合(table
  439. db.createCollection(“collName”, {size: 20, capped: 5, max: 100});//创建成功会显示{“ok”:1}
  440. //判断集合是否为定容量db.collName.isCapped();
  441.  
  442. 2、得到指定名称的聚集集合(table
  443. db.getCollection("account");
  444.  
  445. 3、得到当前db的所有聚集集合
  446. db.getCollectionNames();
  447.  
  448. 4、显示当前db所有聚集索引的状态
  449. db.printCollectionStats();
  450.  
  451. 三、用户相关
  452. 1、添加一个用户
  453. db.addUser("name");
  454. db.addUser("userName", "pwd123", true); 添加用户、设置密码、是否只读
  455.  
  456. 2、数据库认证、安全模式
  457. db.auth("userName", "123123");
  458.  
  459. 3、显示当前所有用户
  460. show users;
  461.  
  462. 4、删除用户
  463. db.removeUser("userName");
  464.  
  465. 四、聚集集合查询
  466. 1、查询所有记录
  467. db.userInfo.find();
  468. 相当于:select* from userInfo;
  469. 默认每页显示20条记录,当显示不下的情况下,可以用it迭代命令查询下一页数据。注意:键入it命令不能带“;”
  470. 但是你可以设置每页显示数据的大小,用DBQuery.shellBatchSize= 50;这样每页就显示50条记录了。
  471.  
  472. 2、查询去掉后的当前聚集集合中的某列的重复数据
  473. db.userInfo.distinct("name");
  474. 会过滤掉name中的相同数据
  475. 相当于:select distict name from userInfo;
  476.  
  477. 3、查询age = 22的记录
  478. db.userInfo.find({"age": 22});
  479. 相当于: select * from userInfo where age = 22;
  480.  
  481. 4、查询age > 22的记录
  482. db.userInfo.find({age: {$gt: 22}});
  483. 相当于:select * from userInfo where age >22;
  484.  
  485. 5、查询age < 22的记录
  486. db.userInfo.find({age: {$lt: 22}});
  487. 相当于:select * from userInfo where age <22;
  488.  
  489. 6、查询age >= 25的记录
  490. db.userInfo.find({age: {$gte: 25}});
  491. 相当于:select * from userInfo where age >= 25;
  492.  
  493. 7、查询age <= 25的记录
  494. db.userInfo.find({age: {$lte: 25}});
  495.  
  496. 8、查询age >= 23 并且 age <= 26
  497. db.userInfo.find({age: {$gte: 23, $lte: 26}});
  498.  
  499. 9、查询name中包含 mongo的数据
  500. db.userInfo.find({name: /mongo/});
  501. //相当于%%
  502. [code]select * from userInfo where name like ‘%mongo%';
  503.  
  504. 10、查询name中以mongo开头的
  505. db.userInfo.find({name: /^mongo/});
  506. select * from userInfo where name like ‘mongo%';
  507.  
  508. 11、查询指定列nameage数据
  509. db.userInfo.find({}, {name: 1, age: 1});
  510. 相当于:select name, age from userInfo;
  511. 当然name也可以用truefalse,当用ture的情况下河name:1效果一样,如果用false就是排除name,显示name以外的列信息。
  512.  
  513. 12、查询指定列nameage数据, age > 25
  514. db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
  515. 相当于:select name, age from userInfo where age >25;
  516.  
  517. 13、按照年龄排序
  518. 升序:db.userInfo.find().sort({age: 1});
  519. 降序:db.userInfo.find().sort({age: -1});
  520.  
  521. 14、查询name = zhangsan, age = 22的数据
  522. db.userInfo.find({name: 'zhangsan', age: 22});
  523. 相当于:select * from userInfo where name = zhangsan' and age = ‘22';
  524.  
  525. 15、查询前5条数据
  526. db.userInfo.find().limit(5);
  527. 相当于:selecttop 5 * from userInfo;
  528.  
  529. 16、查询10条以后的数据
  530. db.userInfo.find().skip(10);
  531. 相当于:select * from userInfo where id not in (
  532. selecttop 10 * from userInfo
  533. );
  534.  
  535. 17、查询在5-10之间的数据
  536. db.userInfo.find().limit(10).skip(5);
  537.  
  538. 可用于分页,limitpageSizeskip是第几页*pageSize
  539.  
  540. 18or 查询
  541. db.userInfo.find({$or: [{age: 22}, {age: 25}]});
  542. 相当于:select * from userInfo where age = 22 or age = 25;
  543.  
  544. 19、查询第一条数据
  545. db.userInfo.findOne();
  546. 相当于:selecttop 1 * from userInfo;
  547. db.userInfo.find().limit(1);
  548.  
  549. 20、查询某个结果集的记录条数
  550. db.userInfo.find({age: {$gte: 25}}).count();
  551. 相当于:select count(*) from userInfo where age >= 20;
  552.  
  553. 21、按照某列进行排序
  554. db.userInfo.find({sex: {$exists: true}}).count();
  555. 相当于:select count(sex) from userInfo;
  556.  
  557. 五、索引
  558. 1、创建索引
  559. db.userInfo.ensureIndex({name: 1});
  560. db.userInfo.ensureIndex({name: 1, ts: -1});
  561.  
  562. 2、查询当前聚集集合所有索引
  563. db.userInfo.getIndexes();
  564.  
  565. 3、查看总索引记录大小
  566. db.userInfo.totalIndexSize();
  567.  
  568. 4、读取当前集合的所有index信息
  569. db.users.reIndex();
  570.  
  571. 5、删除指定索引
  572. db.users.dropIndex("name_1");
  573.  
  574. 6、删除所有索引索引
  575. db.users.dropIndexes();
  576.  
  577. 六、修改、添加、删除集合数据
  578. 1、添加
  579. db.users.save({name: zhangsan', age: 25, sex: true});
  580. 添加的数据的数据列,没有固定,根据添加的数据为准
  581.  
  582. 2、修改
  583. db.users.update({age: 25}, {$set: {name: 'changeName'}}, false, true);
  584. 相当于:update users set name = ‘changeName' where age = 25;
  585. db.users.update({name: 'Lisi'}, {$inc: {age: 50}}, false, true);
  586. 相当于:update users set age = age + 50 where name = Lisi';
  587. db.users.update({name: 'Lisi'}, {$inc: {age: 50}, $set: {name: 'hoho'}}, false, true);
  588. 相当于:update users set age = age + 50, name = ‘hoho' where name = Lisi';
  589.  
  590. 3、删除
  591. db.users.remove({age: 132});
  592.  
  593. 4、查询修改删除
  594. db.users.findAndModify({
  595. query: {age: {$gte: 25}},
  596. sort: {age: -1},
  597. update: {$set: {name: 'a2'}, $inc: {age: 2}},
  598. remove: true
  599. });
  600. db.runCommand({ findandmodify : "users",
  601. query: {age: {$gte: 25}},
  602. sort: {age: -1},
  603. update: {$set: {name: 'a2'}, $inc: {age: 2}},
  604. remove: true
  605. });
  606.  
  607. update 或 remove 其中一个是必须的参数; 其他参数可选。
  608. 参数 详解 默认值
  609. query 查询过滤条件 {}
  610. sort 如果多个文档符合查询过滤条件,将以该参数指定的排列方式选择出排在首位的对象,该对象将被操作 {}
  611. remove 若为true,被选中对象将在返回前被删除 N/A
  612. update 一个 修改器对象
  613. N/A
  614. new 若为true,将返回修改后的对象而不是原始对象。在删除操作中,该参数被忽略。 false
  615. fields 参见Retrieving a Subset of Fields (1.5.0+)
  616. All fields
  617. upsert 创建新对象若查询结果为空。 示例 (1.5.4+)
  618. false
  619.  
  620. 七、语句块操作
  621. 1、简单Hello World
  622. print("Hello World!");
  623. 这种写法调用了print函数,和直接写入"Hello World!"的效果是一样的;
  624.  
  625. 2、将一个对象转换成json
  626. tojson(new Object());
  627. tojson(new Object('a'));
  628.  
  629. 3、循环添加数据
  630. > for (var i = 0; i < 30; i++) {
  631. ... db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
  632. ... };
  633.  
  634. 这样就循环添加了30条数据,同样也可以省略括号的写法
  635. > for (var i = 0; i < 30; i++) db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
  636.  
  637. 也是可以的,当你用db.users.find()查询的时候,显示多条数据而无法一页显示的情况下,可以用it查看下一页的信息;
  638.  
  639. 4、find 游标查询
  640. > var cursor = db.users.find();
  641. > while (cursor.hasNext()) {
  642. printjson(cursor.next());
  643. }
  644. 这样就查询所有的users信息,同样可以这样写
  645. var cursor = db.users.find();
  646. while (cursor.hasNext()) { printjson(cursor.next); }
  647. 同样可以省略{}号
  648.  
  649. 5、forEach迭代循环
  650. db.users.find().forEach(printjson);
  651. forEach中必须传递一个函数来处理每条迭代的数据信息
  652.  
  653. 6、将find游标当数组处理
  654. var cursor = db.users.find();
  655. cursor[4];
  656. 取得下标索引为4的那条数据
  657. 既然可以当做数组处理,那么就可以获得它的长度:cursor.length();或者cursor.count();
  658. 那样我们也可以用循环显示数据
  659.  
  660. for (var i = 0, len = c.length(); i < len; i++) printjson(c[i]);
  661.  
  662. 7、将find游标转换成数组
  663. > var arr = db.users.find().toArray();
  664. > printjson(arr[2]);
  665.  
  666. 用toArray方法将其转换为数组
  667.  
  668. 8、定制我们自己的查询结果
  669. 只显示age <= 28的并且只显示age这列数据
  670. db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);
  671. db.users.find({age: {$lte: 28}}, {age: true}).forEach(printjson);
  672.  
  673. 排除age的列
  674. db.users.find({age: {$lte: 28}}, {age: false}).forEach(printjson);
  675.  
  676. 9、forEach传递函数显示信息
  677. db.things.find({x:4}).forEach(function(x) {print(tojson(x));});
  678.  
  679. 八、其他
  680. 1、查询之前的错误信息
  681. db.getPrevError();
  682.  
  683. 2、清除错误记录
  684. db.resetError();
  685.  
  686. 查看聚集集合基本信息
  687. 1、查看帮助 db.yourColl.help();
  688. 2、查询当前集合的数据条数 db.yourColl.count();
  689. 3、查看数据空间大小 db.userInfo.dataSize();
  690. 4、得到当前聚集集合所在的db db.userInfo.getDB();
  691. 5、得到当前聚集的状态 db.userInfo.stats();
  692. 6、得到聚集集合总大小 db.userInfo.totalSize();
  693. 7、聚集集合储存空间大小 db.userInfo.storageSize();
  694. 8、Shard版本信息 db.userInfo.getShardVersion()
  695. 9、聚集集合重命名 db.userInfo.renameCollection("users"); 将userInfo重命名为users
  696. 10、删除当前聚集集合 db.userInfo.drop();
  697.  
  698. show dbs:显示数据库列表
  699. show collections:显示当前数据库中的集合(类似关系数据库中的表)
  700. show users:显示用户
  701. use <db name>:切换当前数据库,这和MS-SQL里面的意思一样
  702. db.help():显示数据库操作命令,里面有很多的命令
  703. db.foo.help():显示集合操作命令,同样有很多的命令,foo指的是当前数据库下,一个叫foo的集合,并非真正意义上的命令
  704. db.foo.find():对于当前数据库中的foo集合进行数据查找(由于没有条件,会列出所有数据)
  705. db.foo.find( { a : 1 } ):对于当前数据库中的foo集合进行查找,条件是数据中有一个属性叫a,且a的值为1

Linux下的Mongodb部署应用梳理的更多相关文章

  1. 在linux下用tomcat部署java web项目的过程与注意事项

    在linux下用tomcat部署java web项目的过程与注意事项 一.安装JDK 到http://www.oracle.com/technetwork/java/javase/downloads/ ...

  2. linux下实现自动部署tomcat的脚本

    linux下实现自动部署tomcat的脚本 由于经常部署war到tomccat上,经常有一些重复的工作要做:停服务.备份war包.上传新的war包.启动服务.索性就写了一个自动部署的脚本. 脚本如下a ...

  3. Linux下Tomcat同时部署两个工程然而只有一个能访问问题

    Linux下Tomcat同时部署两个工程然而只有一个能访问问题 问题: Linux下单个部署到Tomcat下的时候都正常,两个一起部署,只有一个能访问: 解决方案: 由于采用#./shutdown.s ...

  4. 在linux下用tomcat部署java web项目的过程与注意事项(转)

    在linux下用tomcat部署java web项目的过程与注意事项一.安装JDK到http://www.oracle.com/technetwork/java/javase/downloads/in ...

  5. Linux下Apache服务部署静态网站------网站服务程序

    文章链接(我的CSDN博客): Linux下Apache服务部署静态网站------网站服务程序

  6. MongoDB和Java(1):Linux下的MongoDB安装

    最近花了一些时间学习了下MongoDB数据库,感觉还是比较全面系统的,涉及了软件安装.客户端操作.安全认证.副本集和分布式集群搭建,以及使用Spring Data连接MongoDB进行数据操作,收获很 ...

  7. Linux下使用JDK11部署Nacos启动报错:Could not find or load main class

    Linux下使用JDK11部署Nacos 错误日志 /nacos/jdk-11.0.12/bin/java -server -Xms2g -Xmx2g -Xmn1g -XX:MetaspaceSize ...

  8. Linux下安装MongoDB

    MongoDB是一个C++编写的基于分布式文件存储的数据库,是一个介于关系和非关系之间的数据库,当然也属于NoSQL的行列,存储方式和Redis类似,是json格式的kav-value存储方式,只是R ...

  9. Linux学习、Mongodb部署 踩到的坑学习

    一.安装Centos 7虚拟机系统 1.系统安装 下载阿里云的镜像,下载后安装,默认全程图形界面:虚拟机使用Win10自带的Hyper:碰到的坑记录下 1.在Hyper加载镜像启动的时候,提示“虚拟机 ...

随机推荐

  1. AspNetCore2 Hangfire定时任务

    Hangfire 是一个简单的用于.net及.net core 应用程序,通过数据库持久化,定时执行后台任务的组件 1.通过NuGet安装Hangfire 2.在Startup.cs文件的Config ...

  2. Shell的基础介绍和案例

    一.shell脚本基础 1.第一个脚本 vim  first.sh 分别使用三种方法可以执行脚本:   ./first.sh (需要有可执行的权限)   sh    first.sh   .  fir ...

  3. 记录:一个SQL SERVER奇怪的问题。

    今天遇到了一个奇怪的问题.始终没搞清楚是怎么回事.先记一下 1.首先有张表a,包含字段 编号.日期(varchar(250)),数值 发生日期字段有非正常日期字符串,有NULL,空字符串,可能是误触键 ...

  4. January 12th, 2018 Week 02nd Friday

    Nothing behind me, everything ahead of me, as is ever so on the road. 我的身后空空荡荡,整个世界都在前方,这就是在路上. That ...

  5. Alpha冲刺! Day5 - 砍柴

    Alpha冲刺! Day5 - 砍柴 今日已完成 晨瑶:review了业务逻辑表格,确定了工具类具体函数有哪些:讨论确定了记录的存储方式为HTML. 昭锡:继续学习Gson,并写出json基本操作的D ...

  6. 17秋 软件工程 第六次作业 Beta冲刺 Scrum5

    17秋 软件工程 第六次作业 Beta冲刺 Scrum5 各个成员冲刺期间完成的任务 世强:完成APP端相册.部员管理.手势签到模块: 陈翔:完成Scrum博客.总结博客,完成超级管理员前后端对接: ...

  7. leetcode 7. Reverse Integer [java]

    public int reverse(int x) { long res = 0; while (x != 0){ res = res* 10 + x % 10; x /= 10; } if(res ...

  8. PHP实现DES加密,解决乱码

    PHP要实现DES加密,大体上有2个思路.一是用扩展,一是原生PHP实现. 这里推荐一个PHP原生实现的加密,是thinkphp的一个类库: https://github.com/top-think/ ...

  9. ethereum/EIPs-160 EXP cost increase

    eip title author type category status created 160 EXP cost increase Vitalik Buterin Standards Track ...

  10. layui关闭弹出层

    layui关闭弹出层,今天我在vscode中使用p parent.layer.closeAll()发现没效果 换成layer.closeAll()就解决了这个问题. 由此我觉得关闭layui关闭弹出层 ...