zoukankan      html  css  js  c++  java
  • 5. MongoDB基本操作语句

    转自:http://blog.51cto.com/shanqiangwu/1653577

      1 #MongoDB中有三元素:数据库,集合,文档,其中“集合”就是对应关系数据库中的“表”,“文档”对应“行”。
      2  
      3 #创建数据库testdb数据库,使用以下语句
      4 mongos> use testdb;
      5 #查询数据库,要显示数据库必须插入至少一条文档
      6 mongos> show dbs;
      7 #插入数据文档
      8 mongos> db.tablename.insert({"name":"antian"});
      9 #数据库生成了
     10 mongos> show dbs;
     11 testdb  0.078GB
     12  
     13 #删除数据库
     14 #查询数据库
     15 mongos> show dbs;
     16 testdb  0.078GB
     17 #进入数据库
     18 mongos> use testdb;
     19 #删除数据库
     20 mongos> db.dropDatabase();
     21 { "dropped" : "testdb", "ok" : 1 }
     22 #查询数据库
     23 mongos> show dbs;
     24  
     25 #MongoDB数据类型
     26 MongoDB支持许多数据类型的列表下面给出:
     27 String : 这是最常用的数据类型来存储数据。在MongoDB中的字符串必须是有效的UTF-8。
     28 Integer : 这种类型是用来存储一个数值。整数可以是32位或64位,这取决于您的服务器。
     29 Boolean : 此类型用于存储一个布尔值 (true/ false) 。
     30 Double : 这种类型是用来存储浮点值。
     31 Min/ Max keys : 这种类型被用来对BSON元素的最低和最高值比较。
     32 Arrays : 使用此类型的数组或列表或多个值存储到一个键。
     33 Timestamp : 时间戳。这可以方便记录时的文件已被修改或添加。
     34 Object : 此数据类型用于嵌入式的文件。
     35 Null : 这种类型是用来存储一个Null值。
     36 Symbol : 此数据类型用于字符串相同,但它通常是保留给特定符号类型的语言使用。
     37 Date : 此数据类型用于存储当前日期或时间的UNIX时间格式。可以指定自己的日期和时间,日期和年,月,日到创建对象。
     38 Object ID : 此数据类型用于存储文档的ID。
     39 Binary data : 此数据类型用于存储二进制数据。
     40 Code : 此数据类型用于存储到文档中的JavaScript代码。
     41 Regular expression : 此数据类型用于存储正则表
     42  
     43 #创建集合
     44 #进入数据库
     45 mongos> use testdb;
     46 #创建集合
     47 mongos> db.createCollection("mycollection")
     48 mongos> show tables;
     49 mycollection
     50  
     51 #删除集合
     52 #进入数据库
     53 mongos> use testdb;
     54 mongos> show tables;
     55 mycollection
     56 mongos> db.mycollection.drop();
     57 true
     58 mongos> show tables;
     59  
     60 #插入文档
     61 #插入一条文档
     62 mongos> db.tablesname.insert([{"name":"aaaaa","age":"18"}
     63 #插入两条文档
     64 mongos> db.tablesname.insert([{"name":"ddddd","age":"18"},{"name":"eeee","age":"10"}]);
     65 #格式化查询文档
     66 mongos> db.tablename.find().pretty();
     67 #查询一个文档:
     68 mongos> db.tablesname.findOne();
     69  
     70 #更新文档
     71 #显示集合文档
     72 mongos> db.v.find();
     73 { "_id" : ObjectId("55113e5477eaee1608881c84"), "name" : "antian" }
     74 #更新文档
     75 mongos> db.tablename.update({"name":"antian"},{"name":"wuhan"});
     76 #显示集合文档
     77 mongos> db.tablename.find();
     78 { "_id" : ObjectId("55113e5477eaee1608881c84"), "name" : "wuhan" }
     79  
     80 #删除文档
     81 #删除文档内容
     82 mongos> db.tablename.remove({"name":"wuhan"});
     83 #删除文档:db.tablename.drop();
     84  
     85 #投影
     86 db.tablename.find({},{"sip":1,_id:1});
     87  
     88 #限制记录
     89 mongos> db.tablename.find({},{"sip":1,_id:0}).limit(2);
     90  
     91 #排序文档
     92 #降序
     93 mongos> db.tablename.find({},{"age":1,_id:0}).sort({"age":-1});
     94 #升序
     95 mongos> db.tablename.find({},{"age":1,_id:0}).sort({"age":1});
     96  
     97 #创建索引
     98 mongos> db.tablename.ensureIndex({"id":1})
     99  
    100  
    101 #mongos> db.tablesname.stats();         #数据库集合解释
    102 {
    103     "sharded" : false,                    #分片
    104     "primary" : "shard0001",
    105     "ns" : "6xx.testdocument01",      #集合命令
    106     "count" : 2100,                       #集合文档总数
    107     "size" : 504000,                  #集合空间大小,单位为字节
    108     "avgObjSize" : 240,                   #平均对象占用的空间
    109     "numExtents" : 4,                 #连续分配的数据库
    110     "storageSize" : 696320,               #给整个集合分配的空间,当删除集合文档时,这个值不会降低
    111     "lastExtentSize" : 524288,            #最近分配的块的大小
    112     "paddingFactor" : 1,              #
    113     "paddingFactorNote" : "paddingFactor is unused and unmaintained in 3.0. It remains hard coded to 1.0 for compatibility only.",
    114     "userFlags" : 1,
    115     "capped" : false,
    116     "nindexes" : 1,
    117     "totalIndexSize" : 81760,         #所有索引大小的总和
    118     "indexSizes" : {                  #列出集合的所有索引字段,以及索引大小
    119         "_id_" : 81760
    120     },
    121     "ok" : 1
    122 }

    2.

      1 --------------------------------------------------------------------
      2 MongoDB命令管理
      3 --------------------------------------------------------------------
      4  
      5 shell操作数据库
      6  
      7  
      8 一、超级用户相关:
      9  
     10 1. #进入数据库admin
     11  
     12    use admin
     13  
     14 2. #增加或修改用户密码
     15  
     16    db.addUser('name','pwd')
     17  
     18 3. #查看用户列表
     19  
     20    db.system.users.find()
     21  
     22 4. #用户认证
     23  
     24    db.auth('name','pwd')
     25  
     26 5. #删除用户
     27  
     28    db.removeUser('name')
     29  
     30 6. #查看所有用户
     31  
     32    show users
     33  
     34 7. #查看所有数据库
     35  
     36    show dbs
     37  
     38 8. #查看所有的collection
     39  
     40    show collections
     41  
     42 9. #查看各collection的状态
     43  
     44    db.printCollectionStats()
     45  
     46 10. #查看主从复制状态
     47  
     48     db.printReplicationInfo()
     49  
     50 11. #修复数据库
     51  
     52     db.repairDatabase()
     53  
     54 12. #设置记录profiling,0=off 1=slow 2=all
     55  
     56     db.setProfilingLevel(1)
     57  
     58 13. #查看profiling
     59  
     60     show profile
     61  
     62 14. #拷贝数据库
     63  
     64     db.copyDatabase('mail_addr','mail_addr_tmp')
     65  
     66 15. #删除collection
     67  
     68     db.mail_addr.drop()
     69  
     70 16. #删除当前的数据库
     71  
     72     db.dropDatabase()
     73  
     74  
     75  
     76 二、增删改
     77  
     78 1. #存储嵌套的对象
     79  
     80    db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
     81  
     82 2. #存储数组对象
     83  
     84    db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
     85  
     86 3. #根据query条件修改,如果不存在则插入,允许修改多条记录
     87  
     88    db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
     89  
     90 4. #删除yy=5的记录
     91  
     92    db.foo.remove({'yy':5})
     93  
     94 5. #删除所有的记录
     95  
     96    db.foo.remove()
     97  
     98   
     99  
    100 三、索引
    101  
    102 1. #增加索引:1(ascending),-1(descending)
    103  
    104    db.foo.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
    105  
    106 2. #索引子对象
    107  
    108    db.user_addr.ensureIndex({'Al.Em': 1})
    109  
    110 3. #查看索引信息
    111  
    112    db.foo.getIndexes()
    113  
    114    db.foo.getIndexKeys()
    115  
    116 4. #根据索引名删除索引
    117  
    118    db.user_addr.dropIndex('Al.Em_1')
    119  
    120   
    121  
    122 四、查询
    123  
    124 1. #查找所有
    125  
    126    db.foo.find()
    127  
    128 2. #查找一条记录
    129  
    130    db.foo.findOne()
    131  
    132 3. #根据条件检索10条记录
    133  
    134    db.foo.find({'msg':'Hello 1'}).limit(10)
    135  
    136 4. #sort排序
    137  
    138    db.deliver_status.find({'From':'ixigua@sina.com'}).sort({'Dt',-1})
    139    db.deliver_status.find().sort({'Ct':-1}).limit(1)
    140  
    141 5. #count操作
    142  
    143    db.user_addr.count()
    144  
    145 6. #distinct操作,查询指定列,去重复
    146  
    147    db.foo.distinct('msg')
    148  
    149 7. #”>=”操作
    150  
    151    db.foo.find({"timestamp": {"$gte" : 2}})
    152  
    153 8. #子对象的查找
    154  
    155    db.foo.find({'address.city':'beijing'})
    156  
    157  
    158  
    159 五、管理
    160  
    161 1. #查看collection数据的大小
    162  
    163    db.deliver_status.dataSize()
    164  
    165 2. #查看colleciont状态
    166  
    167    db.deliver_status.stats()
    168  
    169 3. #查询所有索引的大小
    170  
    171    db.deliver_status.totalIndexSize()
    172  
    173   
    174  
    175 六、advanced queries:高级查询
    176  
    177 条件操作符 
    178 $gt : > 
    179 $lt : < 
    180 $gte: >= 
    181 $lte: <= 
    182 $ne : !=、<> 
    183 $in : in 
    184 $nin: not in 
    185 $all: all 
    186 $not: 反匹配(1.3.3及以上版本) 
    187  
    188 查询 name <> "bruce" and age >= 18 的数据 
    189 db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}}); 
    190  
    191 查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 
    192 db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)}); 
    193  
    194 查询 age in (20,22,24,26) 的数据 
    195 db.users.find({age: {$in: [20,22,24,26]}}); 
    196  
    197 查询 age取模10等于0 的数据 
    198 db.users.find('this.age % 10 == 0'); 
    199 或者 
    200 db.users.find({age : {$mod : [10, 0]}}); 
    201  
    202 匹配所有 
    203 db.users.find({favorite_number : {$all : [6, 8]}}); 
    204 可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } 
    205 可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } 
    206  
    207 查询不匹配name=B*带头的记录 
    208 db.users.find({name: {$not: /^B.*/}}); 
    209 查询 age取模10不等于0 的数据 
    210 db.users.find({age : {$not: {$mod : [10, 0]}}}); 
    211  
    212 #返回部分字段 
    213 选择返回age和_id字段(_id字段总是会被返回) 
    214 db.users.find({}, {age:1}); 
    215 db.users.find({}, {age:3}); 
    216 db.users.find({}, {age:true}); 
    217 db.users.find({ name : "bruce" }, {age:1}); 
    218 0为false, 非0为true 
    219  
    220 选择返回age、address和_id字段 
    221 db.users.find({ name : "bruce" }, {age:1, address:1}); 
    222  
    223 排除返回age、address和_id字段 
    224 db.users.find({}, {age:0, address:false}); 
    225 db.users.find({ name : "bruce" }, {age:0, address:false}); 
    226  
    227 数组元素个数判断 
    228 对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 
    229 匹配db.users.find({favorite_number: {$size: 3}}); 
    230 不匹配db.users.find({favorite_number: {$size: 2}}); 
    231  
    232 $exists判断字段是否存在 
    233 查询所有存在name字段的记录 
    234 db.users.find({name: {$exists: true}}); 
    235 查询所有不存在phone字段的记录 
    236 db.users.find({phone: {$exists: false}}); 
    237  
    238 $type判断字段类型 
    239 查询所有name字段是字符类型的 
    240 db.users.find({name: {$type: 2}}); 
    241 查询所有age字段是整型的 
    242 db.users.find({age: {$type: 16}}); 
    243  
    244 对于字符字段,可以使用正则表达式 
    245 查询以字母b或者B带头的所有记录 
    246 db.users.find({name: /^b.*/i}); 
    247  
    248 $elemMatch(1.3.1及以上版本) 
    249 为数组的字段中匹配其中某个元素 
    250  
    251 Javascript查询和$where查询 
    252 查询 age > 18 的记录,以下查询都一样 
    253 db.users.find({age: {$gt: 18}}); 
    254 db.users.find({$where: "this.age > 18"}); 
    255 db.users.find("this.age > 18"); 
    256 f = function() {return this.age > 18} db.users.find(f); 
    257  
    258 排序sort() 
    259 以年龄升序asc 
    260 db.users.find().sort({age: 1}); 
    261 以年龄降序desc 
    262 db.users.find().sort({age: -1}); 
    263  
    264 限制返回记录数量limit() 
    265 返回5条记录 
    266 db.users.find().limit(5); 
    267 返回3条记录并打印信息 
    268 db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); 
    269 结果 
    270 my age is 18 
    271 my age is 19 
    272 my age is 20 
    273  
    274 限制返回记录的开始点skip() 
    275 从第3条记录开始,返回5条记录(limit 3, 5) 
    276 db.users.find().skip(3).limit(5); 
    277  
    278 查询记录条数count() 
    279 db.users.find().count(); 
    280 db.users.find({age:18}).count(); 
    281 以下返回的不是5,而是user表中所有的记录数量 
    282 db.users.find().skip(10).limit(5).count(); 
    283 如果要返回限制之后的记录数量,要使用count(true)或者count(非0) 
    284 db.users.find().skip(10).limit(5).count(true); 
    285  
    286 分组group() 
    287 假设test表只有以下一条数据 
    288 { domain: "www.mongodb.org" 
    289 , invoked_at: {d:"2009-11-03", t:"17:14:05"} 
    290 , response_time: 0.05 
    291 , http_action: "GET /display/DOCS/Aggregation" 
    292 } 
    293 使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; 
    294 db.test.group( 
    295 { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} 
    296 , key: {http_action: true} 
    297 , initial: {count: 0, total_time:0} 
    298 , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } 
    299 , finalize: function(out){ out.avg_time = out.total_time / out.count } 
    300 } ); 
    301  
    302 [ 
    303 { 
    304 "http_action" : "GET /display/DOCS/Aggregation", 
    305 "count" : 1, 
    306 "total_time" : 0.05, 
    307 "avg_time" : 0.05 
    308 } 
    309 ] 
    310  
    311   
    312  
    313 Java 应用示例 
    314  
    315 要使用Java操作MongoDB的话,要到官方网站下载一个驱动包,把包导入后,可以尝试来操作了(记得一定要开着服务器) 
    316  
    317 首先介绍一下比较常用的几个类 
    318  
    319 Mongo:连接服务器,执行一些数据库操作的选项,如新建立一个数据库等 
    320  
    321 DB:对应一个数据库,可以用来建立集合等操作 
    322  
    323 DBCollection:对应一个集合(类似表),可能是我们用得最多的,可以添加删除记录等 
    324  
    325 DBObjec:接口和BasicDBObject对象:表示一个具体的记录,BasicDBObject实现了DBObject,因为是key-value的数据结构,所以用起来其实和HashMap是基本一致的 
    326  
    327 DBCursor:用来遍历取得的数据,实现了Iterable和Iterator 
    328  
    329 接下来实际的操作一下,代码如下: 
    330  
    331 import java.net.UnknownHostException; 
    332  
    333 import java.util.List; 
    334  
    335 import java.util.Set; 
    336  
    337 import com.mongodb.BasicDBObject; 
    338  
    339 import com.mongodb.DB; 
    340  
    341 import com.mongodb.DBCollection; 
    342  
    343 import com.mongodb.DBCursor; 
    344  
    345 import com.mongodb.DBObject; 
    346  
    347 import com.mongodb.Mongo; 
    348  
    349 import com.mongodb.MongoException; 
    350  
    351 public class MongoDbTest { 
    352  
    353   public static void main(String[] args) throws UnknownHostException, MongoException { 
    354  
    355     //Mongo m = new Mongo(); 
    356  
    357 //Mongo m = new Mongo("localhost"); 
    358  
    359 //获得数据库服务
    360  
    361 Mongo m = new Mongo("localhost", 27017); 
    362  
    363 //得到数据库mytest
    364  
    365 DB db = m.getDB("mytest"); 
    366  
    367 //得到mytest数据库下所有表名
    368  
    369     Set<String> colls = db.getCollectionNames(); 
    370  
    371     for (String s : colls) { 
    372  
    373 System.out.println(s); 
    374  
    375 } 
    376  
    377 //得到testCollection表
    378  
    379 DBCollection coll = db.getCollection("testCollection"); 
    380  
    381 //new 一个BasicDBObject对象doc
    382  
    383 BasicDBObject doc = new BasicDBObject(); 
    384  
    385 //赋值
    386  
    387     doc.put("name", "MongoDB"); 
    388  
    389     doc.put("type", "database"); 
    390  
    391 doc.put("count", 1); 
    392  
    393 //又new 一个BasicDBObject对象info
    394  
    395     BasicDBObject info = new BasicDBObject(); 
    396  
    397     info.put("x", 203); 
    398  
    399 info.put("y", 102); 
    400  
    401 //把info放入doc
    402  
    403 doc.put("info", info); 
    404  
    405 //向testCollection表中插入一条数据
    406  
    407 coll.insert(doc); 
    408  
    409 //查询一条数据
    410  
    411     DBObject myDoc = coll.findOne(); 
    412  
    413     System.out.println(myDoc); 
    414  
    415      
    416  
    417     //循环插入100条数据到testCollection
    418  
    419     for (int i=0; i < 100; i++) { 
    420  
    421       coll.insert(new BasicDBObject().append("i", i)); 
    422  
    423     } 
    424  
    425  
    426     //Counting Documents in A Collection 
    427  
    428     System.out.println(coll.getCount()); 
    429  
    430  
    431     //Using a Cursor to Get All the Documents 
    432  
    433     DBCursor cur = coll.find(); 
    434  
    435     while(cur.hasNext()) {
    436  
    437 -----------------------------------------------------
    438 DB methods:
    439         db.addUser(username, password[, readOnly=false])
    440         db.auth(username, password)
    441         db.cloneDatabase(fromhost)
    442         db.commandHelp(name) returns the help for the command
    443         db.copyDatabase(fromdb, todb, fromhost)
    444         db.createCollection(name, { size : ..., capped : ..., max : ... } )
    445         db.currentOp() displays the current operation in the db
    446         db.dropDatabase()
    447         db.eval(func, args) run code server-side
    448         db.getCollection(cname) same as db['cname'] or db.cname
    449         db.getCollectionNames()
    450         db.getLastError() - just returns the err msg string
    451         db.getLastErrorObj() - return full status object
    452         db.getMongo() get the server connection object
    453         db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair
    454         db.getName()
    455         db.getPrevError()
    456         db.getProfilingLevel() - deprecated
    457         db.getProfilingStatus() - returns if profiling is on and slow threshold
    458  
    459         db.getReplicationInfo()
    460         db.getSiblingDB(name) get the db at the same server as this one
    461         db.isMaster() check replica primary status
    462         db.killOp(opid) kills the current operation in the db
    463         db.listCommands() lists all the db commands
    464         db.logout()
    465         db.printCollectionStats()
    466         db.printReplicationInfo()
    467         db.printSlaveReplicationInfo()
    468         db.printShardingStatus()
    469         db.removeUser(username)
    470         db.repairDatabase()
    471         db.resetError()
    472         db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }
    473         db.serverStatus()
    474         db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
    475         db.shutdownServer()
    476         db.stats()
    477         db.version() current version of the server
    478         db.getMongo().setSlaveOk() allow queries on a replication slave server
    479         db.fsyncLock() flush data to disk and lock server for backups
    480         db.fsyncUnock() unlocks server following a db.fsyncLock()
    481 >
  • 相关阅读:
    FastDFS的简单使用
    KindEditor的简单使用
    rpc
    SDS——动态字符串
    图的深度优先遍历和广度优先遍历
    innodb和myisam原理
    cap理论
    冒泡排序
    桥接模式
    适配器模式
  • 原文地址:https://www.cnblogs.com/sharpest/p/7830805.html
Copyright © 2011-2022 走看看