zoukankan      html  css  js  c++  java
  • MongoDB学习笔记(二:入门环境配置及与关系型数据库区别总结)

    一、下载及安装MongoDB

    MongoDB下载官网链接:http://www.mongodb.org/downloads

    具体安装步骤教程:http://www.shouce.ren/api/view/a/6191PS:该链接中对MongoDB安装讲解比较详细,通俗易懂。安装教程链接是我从手册网上找到的,下面的总结知识点也是本人从中学习后归纳的一部分,有兴趣的同学不妨收藏一下~

    附百度云下载链接:http://pan.baidu.com/s/1i5QpmiL 密码:lnqj

     

    二、MongoDB可视化工具下载

    个人比较习惯在图形化界面进行相关命令操作,所以在安装完MongoDB后,就顺便找了一个MongoDB可视化工具安装使用。MongoDB可视化工具比较多,通过查找网上相关博客和帖子,发现mongobooster这个可视化工具比较受欢迎。

    Mongobooster官网下载链接:http://mongobooster.com/downloads(记得当时从官网下载时,网速超慢,下面附一个本人当时下载下来的一个版本的百度云链接)

    Mongobooster百度云链接:http://pan.baidu.com/s/1jIhnwVW 密码:wgxw

    Mongobooster安装后具体界面(PS:和使用mysql相关可视化工具很像,用着很不错):

     

    三、MongoDB基本概念及与关系型数据区别

    MongoDB数据库基本概念:

    关系型数据库

    MongoDB

    database(数据库)

    database(数据库)

    table(表)

    collection(集合)

    row()

    document(文档)

    column(列)

    filed()

    index(索引)

    index(索引)

    table joins(表关系)

    primary key(主键)

    自动将_id字段设置为主键

    MongoDB常用的数据类型:

    数据类型

    描述

    String

    字符串,存储数据常用的数据类型,在MongoDB中,UTF-8编码才是合法的

    Integer

    整型数值,用于存储数值,根据你所采用的服务器,可分为32位或64

    Boolen

    布尔值,用于存储布尔值(真/假)

    Double

    双精度浮点值,用于存储浮点值

    Min/Max keys

    将一个值与BSON(二进制的JSON)元素的最低值和最高值相对比

    Arrays

    用于将数组或列表或多个值存储为一个键

    Timestamp

    时间戳,记录文档修改或添加的具体时间

    Object

    用于内嵌文档

    Null

    用于创建空值

    Symbol

    符号。该数据类型基本上等同于字符串类型,但不同的是,它一般用于采用特殊符号类型的语言

    Date

    日期时间,用unix时间格式来存储当前日期或时间。你可以指定自己的日期时间:创建Date对象,传入年月日信息

    Object ID

    对象 ID,用于创建文档的 ID

    Binary Data

    二进制数据,用于存储二进制数据

    Code

    代码类型,用于在文档中存储 JavaScript 代码

    Regular expression

    正则表达式类型,用于存储正则表达式

    MogoDB常用操作命令:

    1、创建数据库:use db_name(例如:use library,创建一个数据库名称为library的数据库)

    2、查看系统所有数据库:show dbs

    3、删除数据库:先使用具体数据库,使用命令use db_name(PS:该命令在有db_name数据库条件下不会创建数据库,没有则重新创建一个db_name数据库),然后使用命令db.dropDatabase()命令

    4、插入文档:db.collection_name.insert(document)

    5、查看文档:db.collection_name.find()

    6、更新文档:db.collection_name.update(<query>,<update>,{upsert:<boolen>,multi:<boolen>,writeConcern:<boolen>})

    7、删除文档:db.collection_name.remove(<query>,<justOne>)

     

    MongoDB操作语句与关系型SQL语句比照对应表:

     

    操作

    格式

    范例

    RDBMS中的类似语句

    等于

    {<key>:<value>}

    db.col.find({"by":"菜鸟教程"}).pretty()

    where by = '菜鸟教程'

    小于

    {<key>:{$lt:<value>}}

    db.col.find({"likes":{$lt:50}}).pretty()

    where likes < 50

    小于或等于

    {<key>:{$lte:<value>}}

    db.col.find({"likes":{$lte:50}}).pretty()

    where likes <= 50

    大于

    {<key>:{$gt:<value>}}

    db.col.find({"likes":{$gt:50}}).pretty()

    where likes > 50

    大于或等于

    {<key>:{$gte:<value>}}

    db.col.find({"likes":{$gte:50}}).pretty()

    where likes >= 50

    不等于

    {<key>:{$ne:<value>}}

    db.col.find({"likes":{$ne:50}}).pretty()

    where likes != 50

          

    附操作MongoDB数据库常见命令(PS:原文链接):

      1 MongoDb 命令查询所有数据库列表  
      2   
      3 CODE:  
      4   
      5 > show dbs  
      6   
      7 如果想查看当前连接在哪个数据库下面,可以直接输入db  
      8 CODE:  
      9   
     10 > db  
     11 Admin  
     12 想切换到test数据库下面  
     13 CODE:  
     14   
     15 > use test  
     16 switched to db test  
     17 > db  
     18 Test  
     19 想查看test下有哪些表或者叫collection,可以输入  
     20 CODE:  
     21 
     22 
     23 > show collections  
     24 system.indexes  
     25 user  
     26 想知道mongodb支持哪些命令,可以直接输入help  
     27 CODE:  
     28 > help  
     29 Dos代码  收藏代码  
     30   
     31     HELP    
     32           show dbs                     show database names    
     33           show collections             show collections in current database    
     34           show users                   show users in current database    
     35           show profile                 show most recent system.profile entries with time >= 1ms    
     36           use <db name>                set curent database to <db name>    
     37           db.help()                    help on DB methods    
     38           db.foo.help()                help on collection methods    
     39           db.foo.find()                list objects in collection foo    
     40           db.foo.find( { a : 1 } )     list objects in foo where a == 1    
     41           it                           result of the last line evaluated; use to further iterate    
     42   
     43 如果想知道当前数据库支持哪些方法:  
     44 CODE:  
     45 
     46 
     47 
     48 > db.help();  
     49 Java代码  收藏代码  
     50   
     51     DB methods:    
     52           db.addUser(username, password) 添加数据库授权用户    
     53           db.auth(username, password)                访问认证    
     54           db.cloneDatabase(fromhost) 克隆数据库    
     55           db.commandHelp(name) returns the help for the command    
     56           db.copyDatabase(fromdb, todb, fromhost)  复制数据库    
     57           db.createCollection(name, { size : ..., capped : ..., max : ... } ) 创建表    
     58           db.currentOp() displays the current operation in the db    
     59           db.dropDatabase()        删除当前数据库    
     60           db.eval_r(func, args) run code server-side    
     61           db.getCollection(cname) same as db['cname'] or db.cname    
     62           db.getCollectionNames()        获取当前数据库的表名    
     63           db.getLastError() - just returns the err msg string    
     64           db.getLastErrorObj() - return full status object    
     65           db.getMongo() get the server connection object    
     66           db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair    
     67           db.getName()    
     68           db.getPrevError()    
     69           db.getProfilingLevel()    
     70           db.getReplicationInfo()    
     71           db.getSisterDB(name) get the db at the same server as this onew    
     72           db.killOp() kills the current operation in the db    
     73           db.printCollectionStats()   打印各表的状态信息    
     74           db.printReplicationInfo()        打印主数据库的复制状态信息    
     75           db.printSlaveReplicationInfo()        打印从数据库的复制状态信息    
     76           db.printShardingStatus()                打印分片状态信息    
     77           db.removeUser(username) 删除数据库用户    
     78           db.repairDatabase() 修复数据库    
     79           db.resetError()    
     80           db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }    
     81           db.setProfilingLevel(level) 0=off 1=slow 2=all    
     82           db.shutdownServer()    
     83           db.version() current version of the server    
     84 
     85 如果想知道当前数据库下的表或者表collection支持哪些方法,可以使用一下命令如:  
     86 CODE:  
     87   
     88 > db.user.help();  user为表名  
     89 Java代码  收藏代码  
     90   
     91     DBCollection help    
     92           db.foo.count()                统计表的行数    
     93           db.foo.dataSize()        统计表数据的大小    
     94           db.foo.distinct( key ) - eg. db.foo.distinct( 'x' )                按照给定的条件除重    
     95           db.foo.drop() drop the collection 删除表    
     96           db.foo.dropIndex(name)  删除指定索引    
     97           db.foo.dropIndexes() 删除所有索引    
     98           db.foo.ensureIndex(keypattern,options) - options should be an object with these possible fields: name, unique, dropDups  增加索引    
     99           db.foo.find( [query] , [fields]) - first parameter is an optional query filter. second parameter is optional set of fields to return.     
    100   
    101   
    102 根据条件查找数据  
    103 -----------------------  
    104 通过条件查询: db.foo.find( { x : 77 } , { name : 1 , x : 1 } )  
    105 -----------------------------  
    106 
    107 如果想知道当前数据库下的表或者表collection支持哪些方法,可以使用一下命令如:  
    108 CODE:  
    109   
    110 > db.user.help();  user为表名  
    111 Java代码  收藏代码  
    112   
    113     DBCollection help    
    114           db.foo.count()                统计表的行数    
    115           db.foo.dataSize()        统计表数据的大小    
    116           db.foo.distinct( key ) - eg. db.foo.distinct( 'x' )                按照给定的条件除重    
    117           db.foo.drop() drop the collection 删除表    
    118           db.foo.dropIndex(name)  删除指定索引    
    119           db.foo.dropIndexes() 删除所有索引    
    120           db.foo.ensureIndex(keypattern,options) - options should be an object with these possible fields: name, unique, dropDups  增加索引    
    121           db.foo.find( [query] , [fields]) - first parameter is an optional query filter. second parameter is optional set of fields to return.     
    122   
    123   
    124 根据条件查找数据  
    125 -----------------------  
    126 通过条件查询: db.foo.find( { x : 77 } , { name : 1 , x : 1 } )  
    127 -----------------------------  
    128              instead of connecting to a mongod instance  
    129 -v [ --verbose ]         be more verbose (include multiple times for more  
    130                          verbosity e.g. -vvvvv)  
    131 -o [ --out ] arg (=dump) output directory  
    132 [falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongodump -d test -o test/  
    133 connected to: 127.0.0.1  
    134 DATABASE: test         to         test/test  
    135       test.user to test/test/user.bson  
    136                100000 objects  
    137       test.system.indexes to test/test/system.indexes.bson  
    138                1 objects  
    139 [falcon@www.fwphp.cn  ~/mongodb/bin]$ ls  
    140 2     mongo   mongodump    mongofiles   mongorestore  mongosniff  
    141 dump  mongod  mongoexport  mongoimport  mongos     test  
    142 MongoDB的数据恢复工具mongorestore  
    143   
    144 查看test库中的表  
    145 CODE:  
    146   
    147 > show collections  
    148 system.indexes  
    149 User  
    150 删除user表  
    151 CODE:  
    152   
    153 > db.user.drop();  
    154 True  
    155 
    156 > show collections  
    157 System.indexes  
    158 现在利用mongorestore表恢复刚才利用mongodump备份的数据  
    159 CODE:  
    160   
    161 [falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongorestore --help  
    162 usage: ./mongorestore [options] [directory or filename to restore from]  
    163 options:  
    164 --help                  produce help message  
    165 -h [ --host ] arg       mongo host to connect to  
    166 -d [ --db ] arg         database to use  
    167 -c [ --collection ] arg collection to use (some commands)  
    168 -u [ --username ] arg   username  
    169 -p [ --password ] arg   password  
    170 --dbpath arg            directly access mongod data files in this path,  
    171                         instead of connecting to a mongod instance  
    172 -v [ --verbose ]        be more verbose (include multiple times for more  
    173                         verbosity e.g. -vvvvv)  
    174   
    175 [falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongorestore -d test -c user test/test/user.bson  
    176 connected to: 127.0.0.1  
    177 test/test/user.bson  
    178        going into namespace [test.user]  
    179   
    180        100000 objects  
    181 User表中的10w条记录已经恢复  
    182 CODE:  
    183   
    184 > show collections  
    185 system.indexes  
    186 user  
    187 > db.user.find();  
    188 { "_id" : ObjectId("4b9c8db08ead0e3347000000"), "uid" : 1, "username" : "Falcon.C-1" }  
    189 { "_id" : ObjectId("4b9c8db08ead0e3347010000"), "uid" : 2, "username" : "Falcon.C-2" }  
    190 { "_id" : ObjectId("4b9c8db08ead0e3347020000"), "uid" : 3, "username" : "Falcon.C-3" }  
    191 { "_id" : ObjectId("4b9c8db08ead0e3347030000"), "uid" : 4, "username" : "Falcon.C-4" }  
    192 { "_id" : ObjectId("4b9c8db08ead0e3347040000"), "uid" : 5, "username" : "Falcon.C-5" }  
    193 .................  
    194 has more  
    195   
    196   
    197   
    198   
    199   
    200    1. 超级用户相关:  
    201   
    202          #增加或修改用户密码  
    203   
    204          db.addUser('admin','pwd')  
    205   
    206          #查看用户列表  
    207   
    208          db.system.users.find()  
    209   
    210          #用户认证  
    211   
    212          db.auth('admin','pwd')  
    213   
    214          #删除用户  
    215   
    216          db.removeUser('mongodb')  
    217 
    218    #查看所有用户  
    219   
    220          show users  
    221   
    222          #查看所有数据库  
    223   
    224          show dbs  
    225   
    226          #查看所有的collection  
    227   
    228          show collections  
    229   
    230          #查看各collection的状态  
    231   
    232          db.printCollectionStats()  
    233   
    234          #查看主从复制状态  
    235   
    236          db.printReplicationInfo()  
    237   
    238          #修复数据库  
    239   
    240          db.repairDatabase()  
    241   
    242          #设置记录profiling,0=off 1=slow 2=all  
    243   
    244          db.setProfilingLevel(1)  
    245   
    246          #查看profiling  
    247         show profile  
    248   
    249          #拷贝数据库  
    250   
    251          db.copyDatabase('mail_addr','mail_addr_tmp')  
    252   
    253          #删除collection  
    254   
    255          db.mail_addr.drop()  
    256   
    257          #删除当前的数据库  
    258   
    259          db.dropDatabase()  
    260   
    261    2. 客户端连接  
    262   
    263           /usr/local/mongodb/bin/mongo user_addr -u user -p 'pwd'  
    264   
    265    3. 增删改  
    266   
    267            #存储嵌套的对象  
    268   
    269           db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})  
    270   
    271           #存储数组对象  
    272   
    273           db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})  
    274   
    275           #根据query条件修改,如果不存在则插入,允许修改多条记录  
    276    db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)  
    277   
    278           #删除yy=5的记录  
    279   
    280           db.foo.remove({'yy':5})  
    281   
    282           #删除所有的记录  
    283   
    284          db.foo.remove()  
    285   
    286    4. 索引  
    287   
    288           增加索引:1(ascending),-1(descending)  
    289   
    290           db.things.ensureIndex({firstname: 1, lastname: 1}, {unique: true});  
    291   
    292           #索引子对象  
    293   
    294           db.user_addr.ensureIndex({'Al.Em': 1})  
    295   
    296           #查看索引信息  
    297   
    298           db.deliver_status.getIndexes()  
    299   
    300           db.deliver_status.getIndexKeys()  
    301   
    302           #根据索引名删除索引  
    303     db.user_addr.dropIndex('Al.Em_1')  
    304   
    305    5. 查询  
    306   
    307           查找所有  
    308   
    309           db.foo.find()  
    310   
    311           #查找一条记录  
    312   
    313           db.foo.findOne()  
    314   
    315           #根据条件检索10条记录  
    316   
    317           db.foo.find({'msg':'Hello 1'}).limit(10)  
    318   
    319           #sort排序  
    320   
    321           db.deliver_status.find({'From':'yushunzhi@sohu.com'}).sort({'Dt',-1})  
    322   
    323           db.deliver_status.find().sort({'Ct':-1}).limit(1)  
    324   
    325          #count操作  
    326   
    327          db.user_addr.count()  
    328   
    329          #distinct操作  
    330   
    331          db.foo.distinct('msg')  
    332     #>操作  
    333   
    334          db.foo.find({"timestamp": {"$gte" : 2}})  
    335   
    336          #子对象的查找  
    337   
    338          db.foo.find({'address.city':'beijing'})  
    339   
    340    6. 管理  
    341   
    342           查看collection数据的大小  
    343   
    344           db.deliver_status.dataSize()  
    345   
    346           #查看colleciont状态  
    347   
    348           db.deliver_status.stats()  
    349   
    350           #查询所有索引的大小  
    351   
    352           db.deliver_status.totalIndexSize()   

     

     

  • 相关阅读:
    cocos2d-x 坐标系
    Linux 用户和用户组
    Linux 挂载分区 + swap 分区
    Linux 分区 磁盘分区与格式化
    Linux MBR分区(重点知识)
    Linux -磁盘管理 ip http://blog.csdn.net/xh16319/article/details/17272455
    Linux 底行模式常用命令
    Linux Bash 通配符
    Linux Bash 的基本功能 管道符
    Linux Bash的基本功能 输出重定向
  • 原文地址:https://www.cnblogs.com/liuzhen1995/p/5990517.html
Copyright © 2011-2022 走看看