mongodb常用sql

来源:互联网 发布:淘宝网商城男装秋装 编辑:程序博客网 时间:2024/06/05 04:08
这些是我平时经常用到的,部分参考别人的。
window平台安装 MongoDBmongodb D:\Program Files\MongoDB\Server\3.2\binnet start mongodbnet stop mongodb mongo 127.0.0.1:27017  mongo 192.168.101.131:27017 d:cd D:\Program Files\MongoDB\Server\3.2\binmongodb.auth("test", "123456"); //test 123456mongo --host 102.10.123.12 --port 27017  -u 'express'  -p 'express123' expressmongo --host 127.0.0.1 --port 27017 -u 'test'  -p '123456' mongod.exe --bind_ip 127.0.0.1 --logpath "D:\ProgramData\MongoDB\dblog\mongodb.log" --logappend --dbpath "D:\ProgramData\MongoDB\data" --port 27017 --auth --serviceName "MongoDB" --serviceDisplayName "MongoDB" --install  mongod.exe --bind_ip 127.0.0.1 --logpath "D:\ProgramData\MongoDB\dblog\mongodb.log" --logappend --dbpath "D:\ProgramData\MongoDB\data" --port 27017  --serviceName "MongoDB" --serviceDisplayName "MongoDB" --install  MongoDB 下载MongoDB提供了可用于32位和64位系统的预编译二进制包,你可以从MongoDB官网下载安装,MongoDB预编译二进制包下载地址:http://www.mongodb.org/downloads注意:在 MongoDB2.2 版本后已经不再支持 Windows XP 系统。MongoDB for Windows 64-bit 适合 64 位的 Windows Server 2008 R2, Windows 7 , 及最新版本的 Window 系统。MongoDB for Windows 32-bit 适合 32 位的 Window 系统及最新的 Windows Vista。 32 位系统上 MongoDB 的数据库最大为 2GB。MongoDB for Windows 64-bit Legacy 适合 64 位的 Windows Vista, Windows Server 2003, 及 Windows Server 2008 。根据你的系统下载 32 位或 64 位的 .msi 文件,下载后双击该文件,按操作提示安装即可。安装过程中,你可以通过点击 "Custom(自定义)" 按钮来设置你的安装目录。db.classes.update({"count":{$gt:20}},{$set:{"name":"c3"}}) db.getCollection('repay_plan_temp_log').find({})db.getCollection('repay_plan_temp_log').update({},{$set:{'actualPayTime':ISODate('2016-03-30T17:21:28.000+08:00')}},{multi:true}); //$inc:db.getCollection('repay_plan_temp_log').update({},{$inc:{'actualPayTime':-7200000}},{multi:false}); db.getCollection('repay_plan_temp_log').find({},{actualPayTime:1});1、mongo监控状态在下面的例子中,mongostat返回的数据每5分钟(300秒),只要在程序运行。 mongostat收集数据的mongod实例上运行的本地主机接口端口27017。以下两种调用产生相同的行为。mongostat - rowcount 0 300mongostat -N 0 300mongostat 300在下面的例子中,mongostat返回的数据每5分钟一个小时(12次)。mongostat收集数据的mongod实例上运行的本地主机接口端口27017。以下两种调用产生相同的行为。mongostat -rowcount 12 300mongostat -N 12 300在许多情况下,使用 -discover将帮助整组机器的状态,提供更完整的快照。如果Mongos的过程中,连接到一个片式集群上运行在本地机器上的端口27017,你可以使用下面的形式从群集中的所有成员返回统计:mongostat -discover2、数据库复制db.copyDatabase("test","test1");db.copyDatabase("appdb","test1","192.168.101.203:27017");3、锁定admin=db.getSisterDB("admin");admin.runCommand({fsync : 1, lock : 1}); //锁定,只读不可写,写操作阻塞解锁新开cmduse admindb.$cmd.sys.unlock.findOne()3、备份与恢复mongodump -h localhost:27017 -d test1 -o D:\ProgramData\MongoDB\data\backdb.dropDatabase();mongorestore -h localhost:27017 -d test1  D:\ProgramData\MongoDB\data\back\test1db.users.update({name:'user0'},{$set:{'age':10}});db.users.update({name:'user0'},{$inc:{'age':10}});db.users.update({name:"user1"}, {$inc:{age:10}, $set:{sex:1}})2、mongo入门创建数据目录MongoDB将数据目录存储在 db 目录下。但是这个数据目录不会主动创建,我们在安装完成后需要创建它。请注意,数据目录应该放在根目录下((如: C:\ 或者 D:\ 等 )。在本教程中,我们已经在C:盘 安装了 mongodb,现在让我们创建一个data的目录然后在data目录里创建db目录。c:\>cd c:\c:\>mkdir datac:\>cd datac:\data>mkdir dbc:\data>cd dbc:\data\db>你也可以通过window的资源管理器中创建这些目录,而不一定通过命令行。命令行下运行 MongoDB 服务器为了从命令提示符下运行MongoDB服务器,你必须从MongoDB目录的bin目录中执行mongod.exe文件。mongod.exe --dbpath c:\data\db如果执行成功,会输出如下信息:2015-09-25T15:54:09.212+0800 I CONTROL  Hotfix KB2731284 or later update is notinstalled, will zero-out data files2015-09-25T15:54:09.229+0800 I JOURNAL  [initandlisten] journal dir=c:\data\db\journal2015-09-25T15:54:09.237+0800 I JOURNAL  [initandlisten] recover : no journal files present, no recovery needed2015-09-25T15:54:09.290+0800 I JOURNAL  [durability] Durability thread started2015-09-25T15:54:09.294+0800 I CONTROL  [initandlisten] MongoDB starting : pid=2488 port=27017 dbpath=c:\data\db 64-bit host=WIN-1VONBJOCE882015-09-25T15:54:09.296+0800 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R22015-09-25T15:54:09.298+0800 I CONTROL  [initandlisten] db version v3.0.6……mongodb D:\Program Files\MongoDB\Server\3.2\binD:\ProgramData\MongoDB\datamongod.exe --dbpath D:\ProgramData\MongoDB\datamongod.exe --bind_ip 127.0.0.1 --logpath "D:\ProgramData\MongoDB\dblog\mongodb.log" --logappend --dbpath "D:\ProgramData\MongoDB\data" --port 27017 --serviceName "MongoDB" --serviceDisplayName "MongoDB" --install  mongod.exe --remove --serviceName "MongoDB"mongod.exe --bind_ip 127.0.0.1 --logpath "D:\ProgramData\MongoDB\dblog\mongodb.log" --logappend --dbpath "D:\ProgramData\MongoDB\data" --port 27017 --auth --serviceName "MongoDB" --serviceDisplayName "MongoDB" --install  客户端mongovue下表为mongodb启动的参数说明:参数描述--bind_ip绑定服务IP,若绑定127.0.0.1,则只能本机访问,不指定默认本地所有IP--logpath定MongoDB日志文件,注意是指定文件不是目录--logappend使用追加的方式写日志--dbpath指定数据库路径--port指定服务端口号,默认端口27017--serviceName指定服务名称--serviceDisplayName指定服务名称,有多个mongodb服务时执行。--install指定作为一个Windows服务安装。--auth 是否需要认证,MongoDB后台管理 Shell如果你需要进入MongoDB后台管理,你需要先打开mongodb装目录的下的bin目录,然后执行mongo.exe文件,MongoDB Shell是MongoDB自带的交互式Javascript shell,用来对MongoDB进行操作和管理的交互式环境。当你进入mongoDB后台后,它默认会链接到 test 文档(数据库):> mongoMongoDB shell version: 3.0.6connecting to: test……由于它是一个JavaScript shell,您可以运行一些简单的算术运算:> 2 + 24>db 命令用于查看当前操作的文档(数据库):> dbtest>插入一些简单的记录并查找它:> db.runoob.insert({x:10})WriteResult({ "nInserted" : 1 })> db.runoob.find(){ "_id" : ObjectId("5604ff74a274a611b0c990aa"), "x" : 10 }>第一个命令将数字 10 插入到 runoob 集合的 x 字段中。d:cd D:\Program Files\MongoDB\Server\3.2\binmongod.exe --dbpath D:\ProgramData\MongoDB\datamongoshow dbs:显示数据库列表 show collections:显示当前数据库中的集合(类似关系数据库中的表) show users:显示用户use test;db.stats();db.currentOp();db.serverStatus();db.system.users.find();db.addUser("test","test"));db.system.users.find();db.userInfo.insert({"age":22,"name":"test22",sex:"male"});db.userInfo.insert({"age":23,"name":"test23",sex:"male"});db.userInfo.insert({"age":23,"name":"test24",sex:"male"});db.userInfo.find({'age':21}) ;db.userInfo.find()   //查询test中所有数据db.userInfo.find({_id:“1”})   //查询test中id为1的文档db.userInfo.find({age: {$gt: 22}});    //查询age > 22的记录db.userInfo.find({age: {$gte: 23, $lte: 26}});    //查询age >= 23 并且 age <= 26db.userInfo.find({name: /test/});   //查询name中包含 mongo的数据db.userInfo.find({}, {name: 1, age: 1});   //查询指定列name、age数据db.userInfo.find().sort({age: 1});   //按照年龄升序排序db.userInfo.find().sort({age: -1});db.userInfo.find().sort({age:1}).skip(1).limit(2)db.userInfo.find().limit(10).skip(20);    //查询在20-30之间的数据(分页)db.userInfo.find({$or: [{age: 22}, {age: 25}]});   //条件或查询db.userInfo.find({age: {$gte: 25}}).count();  //查询条数db.userInfo.find({_id:{$in:[2,3,4,5,6]}});   //in操作db.userInfo.find({$or:[{age:{$in:[22,23]}},{name:'test24'}]})db.getCollection('userInfo').find();mongostat --rowcount 2 1 --host 192.168.101.203:27017//查看当前时间戳连接数等信息 db.help()B methods:       db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ just calls db.runCommand(...) ]       db.auth(username, password)       db.cloneDatabase(fromhost)       db.commandHelp(name) returns the help for the command       db.copyDatabase(fromdb, todb, fromhost)       db.createCollection(name, { size : ..., capped : ..., max : ... } )       db.createUser(userDocument)       db.currentOp() displays currently executing operations in the db       db.dropDatabase()       db.eval() - deprecated       db.fsyncLock() flush data to disk and lock server for backups       db.fsyncUnlock() unlocks server following a db.fsyncLock()       db.getCollection(cname) same as db['cname'] or db.cname       db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections       db.getCollectionNames()       db.getLastError() - just returns the err msg string       db.getLastErrorObj() - return full status object       db.getLogComponents()       db.getMongo() get the server connection object       db.getMongo().setSlaveOk() allow queries on a replication slave server       db.getName()       db.getPrevError()       db.getProfilingLevel() - deprecated       db.getProfilingStatus() - returns if profiling is on and slow threshold       db.getReplicationInfo()       db.getSiblingDB(name) get the db at the same server as this one       db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set       db.hostInfo() get details about the server's host       db.isMaster() check replica primary status       db.killOp(opid) kills the current operation in the db       db.listCommands() lists all the db commands       db.loadServerScripts() loads all the scripts in db.system.js       db.logout()       db.printCollectionStats()       db.printReplicationInfo()       db.printShardingStatus()       db.printSlaveReplicationInfo()       db.dropUser(username)       db.repairDatabase()       db.resetError()       db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }       db.serverStatus()       db.setLogLevel(level,<component>)       db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all       db.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the db       db.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the db       db.setVerboseShell(flag) display extra information in shell output       db.shutdownServer()       db.stats()> db.stats(){        "db" : "test",        "collections" : 8,        "objects" : 9,        "avgObjSize" : 64.33333333333333,        "dataSize" : 579,        "storageSize" : 102400,        "numExtents" : 0,        "indexes" : 8,        "indexSize" : 102400,        "ok" : 1}> db.userInfo.help()DBCollection help        db.userInfo.find().help() - show DBCursor help        db.userInfo.bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j        db.userInfo.count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS        db.userInfo.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.        db.userInfo.convertToCapped(maxBytes) - calls {convertToCapped:'userInfo', size:maxBytes}} command        db.userInfo.createIndex(keypattern[,options])        db.userInfo.createIndexes([keypatterns], <options>)        db.userInfo.dataSize()        db.userInfo.deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j        db.userInfo.deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j        db.userInfo.distinct( key, query, <optional params> ) - e.g. db.userInfo.distinct( 'x' ), optional parameters are: maxTimeMS        db.userInfo.drop() drop the collection        db.userInfo.dropIndex(index) - e.g. db.userInfo.dropIndex( "indexName" ) or db.userInfo.dropIndex( { "indexKey" : 1 } )        db.userInfo.dropIndexes()        db.userInfo.ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead        db.userInfo.explain().help() - show explain help        db.userInfo.reIndex()        db.userInfo.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.                                                      e.g. db.userInfo.find( {x:77} , {name:1, x:1} )        db.userInfo.find(...).count()        db.userInfo.find(...).limit(n)        db.userInfo.find(...).skip(n)        db.userInfo.find(...).sort(...)        db.userInfo.findOne([query], [fields], [options], [readConcern])        db.userInfo.findOneAndDelete( filter, <optional params> ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS        db.userInfo.findOneAndReplace( filter, replacement, <optional params> ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDoc        db.userInfo.findOneAndUpdate( filter, update, <optional params> ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument        db.userInfo.getDB() get DB object associated with collection        db.userInfo.getPlanCache() get query plan cache associated with collection        db.userInfo.getIndexes()        db.userInfo.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )        db.userInfo.insert(obj)        db.userInfo.insertOne( obj, <optional params> ) - insert a document, optional parameters are: w, wtimeout, j        db.userInfo.insertMany( [objects], <optional params> ) - insert multiple documents, optional parameters are: w, wtimeout, j        db.userInfo.mapReduce( mapFunction , reduceFunction , <optional params> )        db.userInfo.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor        db.userInfo.remove(query)        db.userInfo.replaceOne( filter, replacement, <optional params> ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j        db.userInfo.renameCollection( newName , <dropTarget> ) renames the collection.        db.userInfo.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name        db.userInfo.save(obj)        db.userInfo.stats({scale: N, indexDetails: true/false, indexDetailsKey: <index key>, indexDetailsName: <index name>})        db.userInfo.storageSize() - includes free space allocated to this collection        db.userInfo.totalIndexSize() - size in bytes of all the indexes        db.userInfo.totalSize() - storage allocated for all data and indexes        db.userInfo.update( query, object[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi        db.userInfo.updateOne( filter, update, <optional params> ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j        db.userInfo.updateMany( filter, update, <optional params> ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j        db.userInfo.validate( <full> ) - SLOW        db.userInfo.getShardVersion() - only for use with sharding        db.userInfo.getShardDistribution() - prints statistics about data distribution in the cluster        db.userInfo.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function        db.userInfo.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set        db.userInfo.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection        db.userInfo.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collectiondb.userInfo.find({},{name:1});//只显示name列,默认包含_iddb.userInfo.find({},{name:0});//不显示name列db.userInfo.find({name:/test/},{name:1,_id:0});//返回name值为/test/,且只显示name列2、切换/创建数据库 use yourDB;  当创建一个集合(table)的时候会自动创建当前数据库3、查询所有数据库 show dbs;4、删除当前使用数据库 db.dropDatabase();5、从指定主机上克隆数据库 db.cloneDatabase(“127.0.0.1”); 将指定机器上的数据库的数据克隆到当前数据库6、从指定的机器上复制指定数据库数据到某个数据库 db.copyDatabase("mydb", "temp", "127.0.0.1");将本机的mydb的数据复制到temp数据库中7、修复当前数据库 db.repairDatabase();8、查看当前使用的数据库 db.getName(); db; db和getName方法是一样的效果,都可以查询当前使用的数据库9、显示当前db状态 db.stats();10、当前db版本 db.version();11、查看当前db的链接机器地址 db.getMongo();Collection聚集集合1、创建一个聚集集合(table) db.createCollection(“col1”, {size: 20, capped: 5, max: 100});2、得到指定名称的聚集集合(table) db.getCollection("account");3、得到当前db的所有聚集集合db.getCollectionNames();4、显示当前db所有聚集索引的状态 db.printCollectionStats();用户相关1、添加一个用户 定义:创建一个数据库新用户用db.createUser()方法,如果用户存在则返回一个用户重复错误。语法:db.createUser(user, writeConcern)    user这个文档创建关于用户的身份认证和访问信息;    writeConcern这个文档描述保证MongoDB提供写操作的成功报告。· user文档,定义了用户的以下形式:{ user: "<name>",  pwd: "<cleartext password>",  customData: { <any information> },  roles: [    { role: "<role>", db: "<database>" } | "<role>",    ...  ]}user文档字段介绍:    user字段,为新用户的名字;    pwd字段,用户的密码;    cusomData字段,为任意内容,例如可以为用户全名介绍;    roles字段,指定用户的角色,可以用一个空数组给新用户设定空角色;    在roles字段,可以指定内置角色和用户定义的角色。    Built-In Roles(内置角色):    1. 数据库用户角色:read、readWrite;    2. 数据库管理角色:dbAdmin、dbOwner、userAdmin;    3. 集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;    4. 备份恢复角色:backup、restore;    5. 所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase    6. 超级用户角色:root      // 这里还有几个角色间接或直接提供了系统超级用户的访问(dbOwner 、userAdmin、userAdminAnyDatabase)    7. 内部角色:__system    PS:关于每个角色所拥有的操作权限可以点击上面的内置角色链接查看详情。· writeConcern文档(官方说明)    w选项:允许的值分别是 1、0、大于1的值、"majority"、<tag set>;    j选项:确保mongod实例写数据到磁盘上的journal(日志),这可以确保mongd以外关闭不会丢失数据。设置true启用。    wtimeout:指定一个时间限制,以毫秒为单位。wtimeout只适用于w值大于1。例如:在products数据库创建用户accountAdmin01,并给该用户admin数据库上clusterAdmin和readAnyDatabase的角色,products数据库上readWrite角色。use productsdb.createUser( { "user" : "accountAdmin01",                 "pwd": "cleartext password",                 "customData" : { employeeId: 12345 },                 "roles" : [ { role: "clusterAdmin", db: "admin" },                             { role: "readAnyDatabase", db: "admin" },                             "readWrite"                             ] },               { w: "majority" , wtimeout: 5000 } )验证:mongo -u accountAdmin01 -p yourpassward --authenticationDatabase products例子:use admin    db.createUser(  {   user: "admin", pwd: "admin",  roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]  } )  db.createUser(?{?user:?"test",?pwd:?"123456",roles:?[?{?role:?"userAdminAnyDatabase",?db:?"admin"?}]}?)mongo -u test -p 123456 --authenticationDatabase admin2、数据库认证、安全模式use admin; db.auth("test", "123456");3、显示当前所有用户 show users;4、删除用户 db.dropUser("admin");db.grantRolesToUser('test',[{role:'readWrite',db:'admin'}]);db.grantRolesToUser('test',[{role:'readWrite',db:'test'}]);db.grantRolesToUser('test',[{role:'dbOwner',db:'test'}]);db.revokeRolesFromUser('admin',[{role:'userAdminAnyDatabase',db:'admin'}])db.changeUserPassword('test','test');db.changeUserPassword('test','123456');db.createRole({    role: "testRole",   privileges: [{ resource: { db: "test", collection: "" }, actions: [ "find" ] }],   roles: []  }) ;show roles;> use admin    > show collections  system.indexes  system.roles  system.users  system.version  > db.system.roles.find();  use test  db.createUser(    {      user: "userkk",      pwd: "userkk",      roles: [ { role: "testRole", db: "test" } ]    }  ) #添加Privileges给角色  db.auth('test','123456'); db.grantPrivilegesToRole("testRole", [{resource:{db:'test',collection:""},actions:["update","listCollections"]} ] ); db.users.remove({age:22})db.updateRole("testRole",{ roles:[{ role: "readWrite",db: "test"}]},{ w:"majority" }) db.users.distinct("age"); 聚集集合查询1、查询所有记录db.userInfo.find();相当于:select* from userInfo;默认每页显示20条记录,当显示不下的情况下,可以用it迭代命令查询下一页数据。注意:键入it命令不能带“;”但是你可以设置每页显示数据的大小,用DBQuery.shellBatchSize= 50;这样每页就显示50条记录了。 2、查询去掉后的当前聚集集合中的某列的重复数据db.userInfo.distinct("name");会过滤掉name中的相同数据相当于:select distict name from userInfo; 3、查询age = 22的记录db.userInfo.find({"age": 22});相当于: select * from userInfo where age = 22; 4、查询age > 22的记录db.userInfo.find({age: {$gt: 22}});相当于:select * from userInfo where age >22; 5、查询age < 22的记录db.userInfo.find({age: {$lt: 22}});相当于:select * from userInfo where age <22; 6、查询age >= 25的记录db.userInfo.find({age: {$gte: 25}});相当于:select * from userInfo where age >= 25; 7、查询age <= 25的记录db.userInfo.find({age: {$lte: 25}}); 8、查询age >= 23 并且 age <= 26db.userInfo.find({age: {$gte: 23, $lte: 26}}); 9、查询name中包含 mongo的数据db.userInfo.find({name: /mongo/});//相当于%%select * from userInfo where name like ‘%mongo%’; 10、查询name中以mongo开头的db.userInfo.find({name: /^mongo/});select * from userInfo where name like ‘mongo%’; 11、查询指定列name、age数据db.userInfo.find({}, {name: 1, age: 1});相当于:select name, age from userInfo;当然name也可以用true或false,当用ture的情况下河name:1效果一样,如果用false就是排除name,显示name以外的列信息。 12、查询指定列name、age数据, age > 25db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});相当于:select name, age from userInfo where age >25; 13、按照年龄排序升序:db.userInfo.find().sort({age: 1});降序:db.userInfo.find().sort({age: -1}); 14、查询name = zhangsan, age = 22的数据db.userInfo.find({name: 'zhangsan', age: 22});相当于:select * from userInfo where name = ‘zhangsan’ and age = ‘22’; 15、查询前5条数据db.userInfo.find().limit(5);相当于:selecttop 5 * from userInfo; 16、查询10条以后的数据db.userInfo.find().skip(10);相当于:select * from userInfo where id not in (selecttop 10 * from userInfo); 17、查询在5-10之间的数据db.userInfo.find().limit(10).skip(5);可用于分页,limit是pageSize,skip是第几页*pageSize 18、or与 查询db.userInfo.find({$or: [{age: 22}, {age: 25}]});相当于:select * from userInfo where age = 22 or age = 25; 19、查询第一条数据db.userInfo.findOne();相当于:selecttop 1 * from userInfo;db.userInfo.find().limit(1); 20、查询某个结果集的记录条数db.userInfo.find({age: {$gte: 25}}).count();相当于:select count(*) from userInfo where age >= 20; 21、按照某列进行排序db.userInfo.find({sex: {$exists: true}}).count();相当于:select count(sex) from userInfo;索引1、创建索引db.userInfo.ensureIndex({name: 1});db.userInfo.ensureIndex({name: 1, ts: -1}); 2、查询当前聚集集合所有索引db.userInfo.getIndexes(); 3、查看总索引记录大小db.userInfo.totalIndexSize();  db.userInfo.renameCollection('users') 4、读取当前集合的所有index信息db.users.reIndex(); 5、删除指定索引db.users.dropIndex("name_1"); 6、删除所有索引索引db.users.dropIndexes(); 修改、添加、删除集合数据1、添加db.users.save({name:'zhangsan',age: 25,sex: "true"});添加的数据的数据列,没有固定,根据添加的数据为准 2、修改db.users.update({age: 25}, {$set: {name: 'changeName'}}, false, true);相当于:update users set name = ‘changeName’ where age = 25; db.users.update({name: 'Lisi'}, {$inc: {age: 50}}, false, true);相当于:update users set age = age + 50 where name = ‘Lisi’; db.users.update({name: 'Lisi'}, {$inc: {age: 50}, $set: {name: 'hoho'}}, false, true);相当于:update users set age = age + 50, name = ‘hoho’ where name = ‘Lisi’; 3、删除db.users.remove({age: 132}); print('hello world');tojson(new Object());for(var i=0;i<5;i++){db.users.insert({age:10+i,name:"name"+i,sex:""+i % 2})}var cursor=db.users.find();while(cursor.hasNext()){printjson(cursor.next());}db.users.find().forEach(printjson);forEach中必须传递一个函数来处理每条迭代的数据信息6、将find游标当数组处理var cursor = db.users.find();cursor[4];取得下标索引为4的那条数据既然可以当做数组处理,那么就可以获得它的长度:cursor.length();或者cursor.count();那样我们也可以用循环显示数据for (var i = 0, len = c.length(); i < len; i++) printjson(c[i]); 7、将find游标转换成数组> var arr = db.users.find().toArray();> printjson(arr[2]);用toArray方法将其转换为数组 8、定制我们自己的查询结果只显示age <= 28的并且只显示age这列数据db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);db.users.find({age: {$lte: 28}}, {age: true}).forEach(printjson);排除age的列db.users.find({age: {$lte: 28}}, {age: false}).forEach(printjson); 9、forEach传递函数显示信息db.users.find({},{name:1}).forEach(function(row) {print(tojson(row)+"test");});mongodb.auth('test','123456');其他1、查询之前的错误信息 db.getPrevError();2、清除错误记录 db.resetError();查看聚集集合基本信息db.createUser(?{?user:?"test",?pwd:?"123456",roles:?[?{?role:?"userAdminAnyDatabase",?db:?"admin"?}]}?)1、查看帮助  db.yourColl.help();2、查询当前集合的数据条数  db.yourColl.count();3、查看数据空间大小 db.userInfo.dataSize();4、得到当前聚集集合所在的db db.userInfo.getDB();5、得到当前聚集的状态 db.userInfo.stats();6、得到聚集集合总大小 db.userInfo.totalSize();7、聚集集合储存空间大小 db.userInfo.storageSize();8、Shard版本信息  db.userInfo.getShardVersion()9、聚集集合重命名 db.userInfo.renameCollection("users"); 将userInfo重命名为users10、删除当前聚集集合 db.userInfo.drop(); db.collection.update( criteria, objNew, upsert, multi )criteria : update的查询条件   (where)objNew?? : update的对象和一些更新的操作符(如$,$inc...)等 (set)upsert?? : 这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。multi??? : mongodb默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。例: db.userInfo.update({name: 'Lisi'}, {$inc: {age: 50}, $set: {name: 'hoho'}}, false, true)//相当于:update userInfo set age = age + 50, name = ‘hoho’ where name = ‘Lisi’;删除 db.collection.remove( criteria, justOne)criteria : update的查询条件   (where)justOne :是否只删除一条数据,默认是false,删除所有查询到的。例:db.userInfo.remove({age: 22});修改查询删除db.users.findAndModify({    query: {age: {$gte: 25}},       sort: {age: -1},      update: {$set: {name: 'a2'}, $inc: {age: 2}},      remove: false});Count  合计数据条目db.userInfo.count(query)  //query:查询条件。   根据query统计条数例:db.userInfo.count({age:23})  //查询age为23的文档个数Distinct  去重db.userInfo.distinct(key)  //key:字段名。 查询出所有不同的key例:db.userInfo.distinct(“age”)  //查询collection中所有不相同的ageGroup 分组操作 db.userInfo.group(param);key:用来分组文档的字段。和keyf两者必须有一个keyf:可以接受一个javascript函数。用来动态的确定分组文档的字段。和key两者必须有一个initial:reduce中使用变量的初始化reduce:执行的reduce函数。函数需要返回值。cond:执行过滤的条件。finallize:在reduce执行完成,结果集返回之前对结果集最终执行的函数。可选的db.users.group( {key : {age:true},   //分组字段  (group by age)initial: {count: 0},       //聚合结果的初始值reduce: function(obj,prev){ prev.count++;},    //聚合操作finalize: function(out){ out.totalAge= out.count * out.age }    //结果处理});db.users.group( {key : {age:true},  initial: {count: 0},    reduce: function(obj,prev){ prev.count++;},finalize: function(out){ out.totalAge= out.count * out.age }});聚合操作db.users.group( {    keyf : function(obj){return {age:obj.age}},   //分组字段  (group by age)    initial: {count: 0,names:""},       //聚合结果的初始值    reduce: function(obj,prev){ prev.count++;prev.names+=obj.name+","},    //聚合操作    finalize: function(out){ out.totalAge = out.count * out.age }    //结果处理});聚合管道:aggregate pipeline数据处理的管道概念:整个流水线,可以理解为一个数据传输的管道;该管道中的每一个工作线程,可以理解为一个整个流水线的一个工作阶段stage,这些工作线程之间的合作是一环扣一环的,下个阶段依赖于上一个阶段的输出,上一个阶段的输出成为本阶段的输入。MongoDB2.2版本引入新的功能聚合框架(Aggregation Framework) ,它是数据聚合的一个新框架,其概念类似于数据处理的管道。 每个文档通过一个由多个节点组成的管道,每个节点有自己特殊的功能(分组、过滤等),文档经过管道处理后,最后输出相应的结果。管道基本的功能有两个:一是对文档进行“过滤”,也就是筛选出符合条件的文档;二是对文档进行“变换”,也就是改变文档的输出形式。其他的一些功能还包括按照某个指定的字段分组和排序等聚合管道的常规操作$project:修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。$match:用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。$limit:用来限制MongoDB聚合管道返回的文档数。$skip:在聚合管道中跳过指定数量的文档,并返回余下的文档。$unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。$group:将集合中的文档分组,可用于统计结果。$sort:将输入文档排序后输出。$geoNear:输出接近某一地理位置的有序文档。总结,数据表的复制 db.runCommand({cloneCollection:”commit.daxue”,from:”198.61.104.31:27017″});数据库的复制 db.copyDatabase(“user”,”user”,”198.61.104.31:27017″);对gridfs也OK哦。部分参考 http://blog.csdn.net/xiaoping8411/article/details/76910641、克隆collection1)克隆远程colletion,使用cloneCollection命令完成将远程的collection复制到本地。命令格式:db.runCommand({cloneCollection:”集合”,from:”原机器”,copyIndexes:false}),copyIndexes:是否复制索引例子:132.42.33.175上test库t1表上有一条数据> db.t1.find(){ “_id” : ObjectId(“4fd9a4bf186cb1b6ac95907d”), “name” : “liangzhangping”, “addr” : “beijing” }132.42.33.190上test库上t1表有两条条数据> db.t1.find(){ “_id” : ObjectId(“4fd9c517dcde2d0e33d08c76″), “name” : “liangzhangping”, “age” : 28 }{ “_id” : ObjectId(“4fda1795a3d56c6a40f2bc26″), “name” : “liangzhangping”, “addr” : “jiangxi” }现在将132.42.33.175上test库t1表的数据克隆到132.42.33.190上test库上t1表上,操作如下:a、登录132.42.33.190机器上执行:> db.runCommand({cloneCollection:”test.t1″,from:”132.42.33.175:28010″}){ “ok” : 1 }b、查看验证> db.t1.find(){ “_id” : ObjectId(“4fd9c517dcde2d0e33d08c76″), “name” : “liangzhangping”, “age” : 28 }{ “_id” : ObjectId(“4fda1795a3d56c6a40f2bc26″), “name” : “liangzhangping”, “addr” : “jiangxi” }{ “_id” : ObjectId(“4fd9a4bf186cb1b6ac95907d”), “name” : “liangzhangping”, “addr” : “beijing” }2)克隆本地collection,mongodb没有提供命令进行本地复制,但我们可以写一个循环插入的方法完成,例如:将source_collection中的数据复制一份到target_collection,代码如下:db.source_collection.find().forEach(function(x){db.target_collection.insert(x)})2、复制数据库,使用copyDatabase命令完成复制数据库,格式:copyDatabase(fromdb,todb,fromhost[,username,password])fromdb:源数据库名称todb:目标数据库名称fromhost:源数据库地址,本地和远程都可以username:远程数据库用户名password:远程数据密码例子:将本地db2库复制本地,并重命名db1> db.copyDatabase(“db2″,”db1″,”localhost”)3、刷新磁盘:将内存中尚未写入磁盘的信息写入磁盘,并锁住对数据库更新的操作,但读操作可以使用,使用runCommand命令,这个命令只能在admin库上执行格式:db.runCommand({fsync:1,async:true})async:是否异步执行lock:1 锁定数据库4、数据压缩:mongodb的存储结构采用了预分配的机制,长期不断的操作,会留下太多的的碎片,从而导致数据库系统越来越慢。repairDatabase命令是mongodb内置的一个方法,它会扫描数据库中的所有数据,并将通过导入/导出来重新整理数据集合,将碎片清理干净现在看压缩前和压缩后的对比数据,如下所示:PRIMARY> db.t1.storageSize()65232896PRIMARY> db.t1.totalSize()81470432PRIMARY> db.repairDatabase(){ “ok” : 1 }PRIMARY> db.t1.storageSize()65232896PRIMARY> db.t1.totalSize()79851584mongodb从复制数据库:db.copyDatabase("active","active","192.168.101.201");db.copyDatabase("ads","ads","192.168.101.201");db.copyDatabase("api","api","192.168.101.201");db.copyDatabase("appdb","appdb","192.168.101.201");db.copyDatabase("holidays","holidays","192.168.101.201");db.copyDatabase("investrecord","investrecord","192.168.101.201");db.copyDatabase("local","local","192.168.101.201");db.copyDatabase("nwsession","nwsession","192.168.101.201");db.copyDatabase("nwsessionnwsession","nwsessionnwsession","192.168.101.201");db.copyDatabase("p2pbackDB","p2pbackDB","192.168.101.201");db.copyDatabase("session","session","192.168.101.201");db.copyDatabase("sit_215","sit_215","192.168.101.201");db.copyDatabase("test","test","192.168.101.201");db.copyDatabase("test","session","192.168.101.201");db.copyDatabase("wxtoken","wxtoken","192.168.101.201");db.copyDatabase("yeepay","yeepay","192.168.101.201"); "age" : 21, "name" : "lisi", "sex" : "male " } "age" : 30, "name" : "qinliu", "sex" : "female" } "age" : 23, "name" : "test23", "sex" : "male" } "age" : 23, "name" : "test24", "sex" : "male" } "name" : "setname", "age" : 35, "sex" : "male" }  1、mongodb设置过期时间 mongo 127.0.0.1:27017db.auth("test","123456");use test;db.createCollection('test');db.test.ensureIndex({"createdAt": 1},{expireAfterSeconds: 60});//设置一分钟       "createdCollectionAutomatically" : true,       "numIndexesBefore" : 1,       "numIndexesAfter" : 2,db.userInfo.renameCollection('users');db.test.insert({"age":22,"name":"test22",sex:"male",createdAt:new Date()});db.test.insert({"age":23,"name":"test23",sex:"male"});db.test.insert({"age":23,"name":"test24",sex:"male"});db.test.find({"createdAt": null});//查找没有createdAt字段或值为null的记录db.test.find({"createdAt": ""});db.test.find({createdAt: {$exists: false}})//查找没有createdAt字段的记录db.test.getIndexes();//查看索引db.getCollection('repay_plan_temp_log').find({backupData:{$exists:true,$in:[null]}}); //有这个字段,而且值为nulldb.getCollection('repay_plan_temp_log').find({backupData:{$ne:null}});//所有不等于null且存在该字段db.getCollection('repay_plan_temp_log').find({backupData:{$exists:true}) ;  //有这个字段,而且值可能为null一、索引基础:    MongoDB的索引几乎与传统的关系型数据库一模一样,这其中也包括一些基本的优化技巧。下面是创建索引的命令:    > db.test.ensureIndex({"username":1})    可以通过下面的名称查看索引是否已经成功建立:    > db.test.getIndexes()    删除索引的命令是:    > db.test.dropIndex({"username":1})    在MongoDB中,我们同样可以创建复合索引,如:    -- 数字1表示username键的索引按升序存储,-1表示age键的索引按照降序方式存储。    > db.test.ensureIndex({"username":1, "age":-1})    该索引被创建后,基于username和age的查询将会用到该索引,或者是基于username的查询也会用到该索引,但是只是基于age的查询将不会用到该复合索引。因此可以说,如果想用到复合索引,必须在查询条件中包含复合索引中的前N个索引列。然而如果查询条件中的键值顺序和复合索引中的创建顺序不一致的话,MongoDB可以智能的帮助我们调整该顺序,以便使复合索引可以为查询所用。如:    > db.test.find({"age": 30, "username": "stephen"})    对于上面示例中的查询条件,MongoDB在检索之前将会动态的调整查询条件文档的顺序,以使该查询可以用到刚刚创建的复合索引。    我们可以为内嵌文档创建索引,其规则和普通文档没有任何差别,如:    > db.test.ensureIndex({"comments.date":1})    对于上面创建的索引,MongoDB都会根据索引的keyname和索引方向为新创建的索引自动分配一个索引名,下面的命令可以在创建索引时为其指定索引名,如:    > db.test.ensureIndex({"username":1},{"name":"testindex"})        随着集合的增长,需要针对查询中大量的排序做索引。如果没有对索引的键调用sort,MongoDB需要将所有数据提取到内存并排序。因此在做无索引排序时,如果数据量过大以致无法在内存中进行排序,此时MongoDB将会报错。    二、唯一索引:    在缺省情况下创建的索引均不是唯一索引。下面的示例将创建唯一索引,如:    > db.test.ensureIndex({"userid":1},{"unique":true})    如果再次插入userid重复的文档时,MongoDB将报错,以提示插入重复键,如:    > db.test.insert({"userid":5})    > db.test.insert({"userid":5})    E11000 duplicate key error index: test.test.$userid_1  dup key: { : 5.0 }        如果插入的文档中不包含userid键,那么该文档中该键的值为null,如果多次插入类似的文档,MongoDB将会报出同样的错误,如:    > db.test.insert({"userid1":5})    > db.test.insert({"userid1":5})    E11000 duplicate key error index: test.test.$userid_1  dup key: { : null }            如果在创建唯一索引时已经存在了重复项,我们可以通过下面的命令帮助我们在创建唯一索引时消除重复文档,仅保留发现的第一个文档,如:    --先删除刚刚创建的唯一索引。    > db.test.dropIndex({"userid":1})     --插入测试数据,以保证集合中有重复键存在。    > db.test.remove()    > db.test.insert({"userid":5})    > db.test.insert({"userid":5})        --创建唯一索引,并消除重复数据。    > db.test.ensureIndex({"userid":1},{"unique":true,"dropDups":true})        --查询结果确认,重复的键确实在创建索引时已经被删除。    > db.test.find()    { "_id" : ObjectId("4fe823c180144abd15acd52e"), "userid" : 5 }            我们同样可以创建复合唯一索引,即保证复合键值唯一即可。如:    > db.test.ensureIndex({"userid":1,"age":1},{"unique":true})        三、使用explain:    explain是非常有用的工具,会帮助你获得查询方面诸多有用的信息。只要对游标调用该方法,就可以得到查询细节。explain会返回一个文档,而不是游标本身。如:    > db.test.find().explain()    {        "cursor" : "BasicCursor",        "nscanned" : 1,        "nscannedObjects" : 1,        "n" : 1,        "millis" : 0,        "nYields" : 0,        "nChunkSkips" : 0,        "isMultiKey" : false,        "indexOnly" : false,        "indexBounds" : {        }        }    explain会返回查询使用的索引情况,耗时和扫描文档数的统计信息。    "cursor":"BasicCursor"表示没有使用索引。    "nscanned":1 表示查询了多少个文档。    "n":1 表示返回的文档数量。    "millis":0 表示整个查询的耗时。    四、索引管理:    system.indexes集合中包含了每个索引的详细信息,因此可以通过下面的命令查询已经存在的索引,如:    > db.system.indexes.find()    如果在为已有数据的文档创建索引时,可以执行下面的命令,以使MongoDB在后台创建索引,这样的创建时就不会阻塞其他操作。但是相比而言,以阻塞方式创建索引,会使整个创建过程效率更高,但是在创建时MongoDB将无法接收其他的操作。    > db.test.ensureIndex({"username":1},{"background":true})1、replica set复制集复制d:cd D:\Program Files\MongoDB\Server\3.2\binmongod.exe --bind_ip 127.0.0.1 --logpath "D:\ProgramData\MongoDB\dblog1\mongodb.log" --logappend --dbpath "D:\ProgramData\MongoDB\data1" --port 10001 --replSet shard1d:cd D:\Program Files\MongoDB\Server\3.2\binmongod.exe --bind_ip 127.0.0.1 --logpath "D:\ProgramData\MongoDB\dblog2\mongodb.log" --logappend --dbpath "D:\ProgramData\MongoDB\data2" --port 10002 --replSet shard1d:cd D:\Program Files\MongoDB\Server\3.2\binmongo 127.0.0.1:10001cfg={_id:'shard1',members:[ {_id:0,host:'127.0.0.1:10001'}, {_id:1,host:'127.0.0.1:10002'}] } rs.initiate(cfg) rs.status();rs.slaveOK();//secondary上2、添加第三台添加第三个,先启动再添加d:cd D:\Program Files\MongoDB\Server\3.2\binmongod.exe --bind_ip 127.0.0.1 --logpath "D:\ProgramData\MongoDB\dblog3\mongodb.log" --logappend --dbpath "D:\ProgramData\MongoDB\data3" --port 10003 --replSet shard1连接primary节点,执行下面的命令 rs.add('127.0.0.1:10003') rs.addArb('127.0.0.1:10003') //重新配置 rs.reconfig(rs.conf()) shard1:PRIMARY> rs.help();        rs.status()                                { replSetGetStatus : 1 } checks repl set status        rs.initiate()                              { replSetInitiate : null } initiates set with default settings        rs.initiate(cfg)                           { replSetInitiate : cfg } initiates set with configuration cfg        rs.conf()                                  get the current configuration object from local.system.replset        rs.reconfig(cfg)                           updates the configuration of a running replica set with cfg (dis        rs.add(hostportstr)                        add a new member to the set with default attributes (disconnects        rs.add(membercfgobj)                       add a new member to the set with extra attributes (disconnects)        rs.addArb(hostportstr)                     add a new member which is arbiterOnly:true (disconnects)        rs.stepDown([stepdownSecs, catchUpSecs])   step down as primary (disconnects)        rs.syncFrom(hostportstr)                   make a secondary sync from the given member        rs.freeze(secs)                            make a node ineligible to become primary for the time specified        rs.remove(hostportstr)                     remove a host from the replica set (disconnects)        rs.slaveOk()                               allow queries on secondary nodes        rs.printReplicationInfo()                  check oplog size and time range        rs.printSlaveReplicationInfo()             check replica set members and replication lag        db.isMaster()                              check who is primary        reconfiguration helpers disconnect from the database so the shell will display        an error, even if the command succeeds.shard1:PRIMARY> db.isMaster();{        "hosts" : [                "127.0.0.1:10001",                "127.0.0.1:10002"        ],        "setName" : "shard1",        "setVersion" : 1,        "ismaster" : true,        "secondary" : false,        "primary" : "127.0.0.1:10001",        "me" : "127.0.0.1:10001",        "electionId" : ObjectId("7fffffff0000000000000002"),        "maxBsonObjectSize" : 16777216,        "maxMessageSizeBytes" : 48000000,        "maxWriteBatchSize" : 1000,        "localTime" : ISODate("2017-02-10T07:36:45.031Z"),        "maxWireVersion" : 4,        "minWireVersion" : 0,        "ok" : 1}shard1:PRIMARY>


0 0
原创粉丝点击