MongoDB 笔记

常用命令

1 查询所有存在的数据库

show dbs

2 进入数据库

use admin

3 查看所有的collection集合

show collections    

4 增加或修改密码

db.addUser('userTest','123456')

db.addUser("userTest","123456",true) 参数分别为 用户名、密码、是否只读

5 查看用户列表

db.system.users.find()

6 用户认证

db.auth('userTest','123456')

7 删除用户

db.removeUser('userTest')

8 查看所有用户

show users

9 查看各个collection的状态

db.printCollectionStats()

10 查看主从复制状态

db.printReplicationInfo()

11 修复数据库

db.repairDatabase()

12 设置profiling,0:off 1:slow 2 all

db.setProfilingLevel(1)

13 查看profiling

show profiling

14 拷贝数据库

db.copyDatabase('userTest','userTest1')

db.copyDatabase("userTest","temp","127.0.0.1")

15 删除集合collection

db.userTest.drop()

16 删除当前数据库

db.dropDatabase()

MongoDB增删改命令

1 存储数据

    db.collection.insert({'name':'userTest'})
    
    db.collection.save({'age':18})

1 存储嵌套的对象

    db.foo.save({'name':'userTest','age':25,'address':{'city':'changchun','Province':'Jilin'}})

2 存储数组对象

    db.foo.save({'name':userTest,'age':25,'address':['Jilin Province','Liaoning Province']})

3 根据query条件修改,如果不存在则插入,允许修改多条记录

    db.foo.update({'age':'25'},{'$set':{'name':'userTest'}},upsert=true,multi=true)

4 删除yy=5的记录

    db.foo.remove({'name':'userTest'})

5 删除所有的记录

    db.foo.remove()
    

6 去掉某个字段 $unset

  db.users.update({},{'$unset':{'age':1}},false,true);
    

索引

1 增加索引:1 asc -1 desc

db.foo.ensureIndex({firstname:1,lastname:-1},{unieap:true})

2 索引子对象

db.foo.ensureIndex({'Al.Em':!})

3 查看索引信息

db.foo.getIndexes()

db.foo.getIndexKeys()

4 根据索引名删除索引

db.foo.dropIndex('Al.Em_1')

查询

$gt ---- >
$lt ---- <
$gte ---- >=
$lte ---- <=
$ne ---- != 、<>
$in ---- in
$nin ---- not in
$all ---- all
$or ---- or
$not ---- 反匹配

1 查询所有记录

db.foo.find() ---- select * from foo

2 查询某列非重复的记录

db.foo.distinct("userTest") ---- select distinct name from foo

3 查询age = 22 的记录

db.foo.find({"age":22}) ---- select * from foo where age = 22

4 查询age > 22 的记录

db.foo.find({age:{$gt:22}}) ---- select * from foo where age > 22

5 查询age < 22 的记录

db.foo.find({age:{$lt:22}}) ---- select * from foo where age < 22

6 查询age <= 25的记录

db.foo.find({age:{$lte:25}})

7 查询age >= 23 并且 age <=26的记录

db.foo.find({age:{gte:23,lte:26}})

8 查询name中包含userTest的数据

db.foo.find({name:/userTest/}) ---- select * from foo where name like '%userTest%'

9 查询name中以userTest开头的数据

db.foo.find({name:/^userTest/}) ---- select * from foo where name like 'userTest%'

10 查询指定列name、age的数据

db.foo.find({},{name:1,age:1}) ---- select name,age from foo

11 查询制定列name、age数据,并且age > 22

db.foo.find({age:{$gt:22}},{name:1,age:1}) ---- select name,age from foo where age >22

12 按照年龄排序

  • 升序:db.foo.find().sort({age:1}) 降序:db.foo.find().sort({age:-1})

13 查询name=userTest.age=25的数据

db.foo.find({name:'userTest',age:22}) ---- select * from foo where name='userTest' and age ='25'

14 查询前5条数据

db.foo.find().limit(5) ---- select top 5 * from foo

15 查询10条以后的数据

db.foo.find().skip(10) ---- select * from foo where id not in (select top 10 * from foo);

16 查询在5-10之间的数据

db.foo.find().limit(10).skip(5) 

17 or与查询

db.foo.find({$or:[{age:22},{age:25}]}) ---- select * from foo where age=22 or age =25

18 查询第一条数据

db.foo.findOne() 、db.foo.find().limit(1)---- select top 1 * from foo

19 查询某个结果集的记录条数

db.foo.find({age:{$gte:25}}).count() ---- select count(*) from foo where age >= 20

20 按照某列进行排序

db.foo.find({sex:{$exists:true}}).count() ---- select count(sex) from foo

21 查询age取模10等于0的数据

db.foo.find('this.age % 10 == 0')、db.foo.find({age:{$mod:[10,0]}})

22 匹配所有

db.foo.find({age:{$all:[22,25]}})

23 查询不匹配name=X*带头的记录

db.foo.find({name:{$not:/^X.*/}})

24 排除返回age字段

db.foo.find({name:'userTest'},{age:0})

25 判断字段是否存在

db.foo.find({name:{$exists:true}})    

26 查询两个字段值相同的记录

db.foo.find({$where:"this.bluid==this.seqid"}).count();

MongoDB下根据数组大小进行查询的方法

1.测试数据

db.array_test.insert({name:'a', num:[11,22,33,44,55]});
db.array_test.insert({name:'b', num:[111,222]});
db.array_test.insert({name:'c', num:[1111]});
db.array_test.insert({name:'d', num:[2222]});
  1. $size 查询指定大小的数据

    db.array_test.find({num:{$size:2}})

  • 注意:$size 无法查询某个范围的大小,例如下面的语句是无法按照预期运行的:

    db.array_test.find({num:{$size:{$gt:3}}}); //错误

官方文档中建议,如果需要查询的数组大小在某个范围,可以另外为每个文档添加一个键来保存当前数组的大小。

2.其他思路:

使用$where,例如如果要求数组大小小于3:

db.array_test.find({ $where: "this.num.length < 3" }).pretty()

这种方法具有很大的灵活性,但是速度会慢一些。

另外一个比较高效的方法是判断数组中的某个指定索引的元素是否存在,例如如果要求数组大小小于3:

db.array_test.find({ "num.2": {$exists:0} })

数组大小小于3,也就是num[2]不存在。

db.array_test.find({ "num.3": {$exists:1} })

数据大于等于 3

aggregate

1 分组查询

    db.users.aggregate([
    {$match : {'_created':{'$gte': ISODate('2017-04-01 0:0:0')}}},
    {$group : {_id : "$channel", channel_count:{$sum:1}}},
    {$sort:{channel_count:-1}}
    ]);
    

2 多次分组查询

    db.logins.aggregate([
    {'$match': {'operate': 'get_token'}}, 
    {'$group': {'_id': {'userId': '$user_id', 'brand': '$brand', 'deviceType': '$src'}}}, 
    {'$group': {'_id': {'brand': '$_id.brand', 'deviceType': '$_id.deviceType'}, 'num': {'$sum': 1}}}, 
    {'$sort': {'_id.deviceType': -1, 'num': -1}}, 
    {'$limit': 20}]);

各种更新操作

  • 更新语法

      db.collection.update(criteria, objNew, upsert, multi )
    
  • criteria:update的查询条件,类似sql update查询内where后面的

  • objNew:update的对象和一些更新的操作符(如$,$inc…)等,也可以理解为sql update查询内set后面的。

  • upsert : 如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。

  • multi : mongodb默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。

1 修改字段数据类型语法

  • MongoDB 数据类型

      db.users.find({"recv":{$type:2}}).forEach(  
               function(x){  
                   x.recv=new NumberLong(x.recv);  
                   db.users.save(x);  
               }  
          );
    

2 mongodb 更新一个字段的值为另外一个字段的值

    db.users.find({'client.src':2}).forEach(
       function(item){                 
           db.users.update({"_id":item._id},{"$set":{"client.deviceName":item.client.sysDesc}},false,true) 
        }
    )

3 mongoDB 同步collection从一个数据库到另一个数据库中

  • new_database是目的数据库

      db.<collection_name>.find().forEach(function(d){ db.getSiblingDB('<new_database>')['<collection_name>'].insert(d); });
    

管理

1 查看collection数据大小

db.userTest.dataSize()

2 查看collection状态

db.userTest.stats()

3 查询所有索引的大小

db.userTest.totalIndexSize()

mongoDB关于数据库的操作

User相关的基本操作:

    > show users                        ------查看所有用户
    > db.system.users.find()              ------查看用户列表
    > db.addUser('name','pwd')                           ------增加或修改用户密码
    > db.addUser("userName", "pwd123", true)      ------添加用户、设置密码、是否只读
    > db.auth("userName", "123123")                  ------数据库认证、安全模式
    > db.removeUser('name')                               ------根据用户名删除用户

Database相关的基本操作:

    > show dbs                                                                           ------查看所有数据库
    > use [db-name]                                                                  ------当创建一个集合(table)的时候会自动创建当前数据库,这个指令相当于mysql的use [database-name]
    > db.dropDatabase()                                                          ------删除当前的数据库
    > db.repairDatabase()                                                        ------修复数据库
    > db.copyDatabase('mail_addr','mail_addr_tmp')         -----拷贝数据库
    > db.copyDatabase("mydb", "temp", "127.0.0.1")          ------将本机的mydb的数据复制到temp数据库中
    > db.cloneDatabase(“127.0.0.1”)                                     ------将指定机器上的数据库的数据克隆到当前数据库
    

Collection相关的基本操作:

    > show collections                                                             ------查看所有的集合 
    > db.printReplicationInfo()                                             ------查看主从复制状态
    > db.mail_addr.drop()                                                     ------删除collection(mail_addr 是collections的名字)
    > db.createCollection(“collectionName”, {size: 20, capped: 5, max: 100})            ------创建一个聚集集合
    > db.getCollection("account")                                        ------得到指定名称的聚集集合
    > db.getCollectionNames()                                             ------得到当前db的所有聚集集合
    > db.printCollectionStats()                                              ------查看各collection的状态
    其它:
    > db.getPrevError()                                                          ------查询之前的错误信息
    > db.resetError()                                                               ------清除错误记录
    
    

查看聚集集合的基本信息

    > db.test.count();                  ------查询当前集合的数据条数
    > db.test.dataSIze();                                                   ------查询数据空间大小
    > db.test.getDB();                                                       ------得到当前聚集集合所在的database
    > db.test.stats();                                                          ------得到当前聚集的状态
    > db.test.totalSize();                                                ------得到聚集集合总大小
    > db.test.storageSize();                                             ------得到聚集集合储存空间大小
    > db.test.getShardVersion();                                    ------Shard版本信息
    > db.test.renameCollection("users");                     ------将集合test重名为users
    > db.test.drop();                                                          ------删除当前聚集集合

mongoDB数据的导入和导出

Mongodb中的mongoexport工具可以把一个collection导出成JSON格式或CSV格式的文件。可以通过参数指定导出的数据项,也可以根据指定的条件导出数据。
      
      
  • 命令选项说明: 

        
      -h:指明数据库宿主机的IP
      -u:指明数据库的用户名
      -p:指明数据库的密码
      -d:指明数据库的名字
      -c:指明collection的名字
      -f:指明要导出那些列
      -o:指明到要导出的文件名
      -q:指明导出数据的过滤条件
    

demo

本地
        mongoexport -d bludb -c resources -o resources.json --type json
        

远程
mongoexport -h IP --port 端口 -u 用户名 -p 密码 -d 数据库名 -c collections名称 -o resources.json --type json

远程
mongoexport -h IP –port 端口 -u 用户名 -p 密码 -d 数据库名 -c collections名称 -o resources.json –type json

Mongodb中的mongoimport工具可以把一个特定格式文件中的内容导入到指定的collection中。该工具可以导入JSON格式数据,也可以导入CSV格式数据

 
导入命令选项说明:   
    -h:指明数据库宿主机的IP
    -u:指明数据库的用户名
    -p:指明数据库的密码
    -d:指明数据库的名字
    -c:指明collection的名字
    -f:指明要导入那些列

demo

    mongoimport -h IP --port 端口 -u 用户名 -p 密码 -d 数据库名 -c colelctions名称  resources.json --type json
    
如果要导入CSV格式文件中的内容,则需要通过–type参数指定导入格式(CSV 格式良好,主流数据库都支持导出为CSV 的格式,所以这种格式非常利于异构数据迁移)
  • 参数说明:

      -type:指明要导入的文件格式
      -headerline:指明第一行是列名,不需要导入
      -file:指明要导入的文件
    

MongoDB的数据备份和恢复

用mongodump 来做MongoDB 的库或表级别的备份

  • 备份选项说明(sudo ./mongodump –help):

      -h:指明数据库宿主机的IP
      -u:指明数据库的用户名
      -p:指明数据库的密码
      -d:指明数据库的名字
      -c:指明collection的名字
      -o:输出目录
      -q:json query(json查询)
    
用mongorestore 来做MongoDB 的库或表级别的数据恢复
  • 恢复选项说明(sudo ./mongorestore –help):

      -u:指明数据库的用户名
      -p:指明数据库的密码
      -d:指明数据库的名字
      -c:指明collection的名字
    

   

从阿里云备份的数据,导入本地

  • 阿里云建议的语法

      cat xx.ar| mongorestore -h xxx --port xxx -u xxx -p xxx --drop --gzip --archive -vvvv --stopOnError
    
  • 我在windows上导入的语法

      mongorestore -h 127.0.0.1 --port 27017  --drop --gzip --archive=hins1226667_data_2212.ar --stopOnError