標籤:flush cpp his 等於 令行 get 注意 www 插入
首先我們先安裝這個資料庫。你能夠使用windows或者linux,但推薦使用的是linux,我使用的是ubuntu12.04.在下方的網址中共能夠下載,基本都是64位的系統。
假設位linux系統也能夠使用命令列安裝,我就是使用sudo apt-get install mongodb。
https://www.mongodb.org/downloads
MongoDB 由 databases 組成,databases 由 collections 組成,collections 由documents(相當於行)組成,而 documents 有 fields(相當於列)組成。
help
最開始應該介紹的就是help函數。學習一個東西最好的文檔就是官方文檔。以下我會給出幾個指令的運行過程。最主要的形式就是db.help(),也能夠在中間加上資料庫的名稱如db.douban.help()。
> db.help()DB methods:db.addUser(username, password[, readOnly=false])db.auth(username, password)db.cloneDatabase(fromhost)db.commandHelp(name) returns the help for the commanddb.copyDatabase(fromdb, todb, fromhost)db.createCollection(name, { size : ..., capped : ..., max : ... } )db.currentOp() displays the current operation in the dbdb.dropDatabase()db.eval(func, args) run code server-sidedb.getCollection(cname) same as db[‘cname‘] or db.cnamedb.getCollectionNames()db.getLastError() - just returns the err msg stringdb.getLastErrorObj() - return full status objectdb.getMongo() get the server connection objectdb.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pairdb.getName()db.getPrevError()db.getProfilingLevel() - deprecateddb.getProfilingStatus() - returns if profiling is on and slow threshold db.getReplicationInfo()db.getSiblingDB(name) get the db at the same server as this onedb.isMaster() check replica primary statusdb.killOp(opid) kills the current operation in the dbdb.listCommands() lists all the db commandsdb.logout()db.printCollectionStats()db.printReplicationInfo()db.printSlaveReplicationInfo()db.printShardingStatus()db.removeUser(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.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=alldb.shutdownServer()db.stats()db.version() current version of the serverdb.getMongo().setSlaveOk() allow queries on a replication slave serverdb.fsyncLock() flush data to disk and lock server for backupsdb.fsyncUnock() unlocks server following a db.fsyncLock()
> db.douban.help()DBCollection helpdb.douban.find().help() - show DBCursor helpdb.douban.count()db.douban.dataSize()db.douban.distinct( key ) - eg. db.douban.distinct( ‘x‘ )db.douban.drop() drop the collectiondb.douban.dropIndex(name)db.douban.dropIndexes()db.douban.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDupsdb.douban.reIndex()db.douban.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return. e.g. db.douban.find( {x:77} , {name:1, x:1} )db.douban.find(...).count()db.douban.find(...).limit(n)db.douban.find(...).skip(n)db.douban.find(...).sort(...)db.douban.findOne([query])db.douban.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, ‘new‘: false] } )db.douban.getDB() get DB object associated with collectiondb.douban.getIndexes()db.douban.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )db.douban.mapReduce( mapFunction , reduceFunction , <optional params> )db.douban.remove(query)db.douban.renameCollection( newName , <dropTarget> ) renames the collection.db.douban.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection namedb.douban.save(obj)db.douban.stats()db.douban.storageSize() - includes free space allocated to this collectiondb.douban.totalIndexSize() - size in bytes of all the indexesdb.douban.totalSize() - storage allocated for all data and indexesdb.douban.update(query, object[, upsert_bool, multi_bool])db.douban.validate( <full> ) - SLOWdb.douban.getShardVersion() - only for use with shardingdb.douban.getShardDistribution() - prints statistics about data distribution in the cluster
use
use deng能夠用來建立 deng,不用操心 deng 不會建立,當建立第一個 collection 時,deng會自己主動建立。
insert
db.unicorns.insert({name: ‘demo‘, sex: ‘m‘, weight: 70}),插入一個資料 collection 為 unicorns。使 用 db.getCollectionNames() , 會 得 到 unicorns 和 system.indexes 。system.indexes 對每一個 DB 都會有,用於記錄 index。
能夠通過find函數查看是否插入成功。
find
db.unicorns.find()會看到 document。就相當於mysql中的select * from table; 查看集合中的全部內容。
使用查詢 db.unicorns.find({name: ‘Dunx‘}) 其它說明: $lt, $lte, $gt, $gte and $ne 分別表示小於、小於等於、大於、大於等於、不等於db.unicorns.find({gender: {$ne: ‘f‘}, weight: {$gte: 701}})$exists 用於表示 field 是否存在db.unicorns.find({vampires: {$exists: false}})or 和 anddb.unicorns.find({gender: ‘f‘, $or: [{loves: ‘apple‘}, {loves: ‘orange‘}, {weight: {$lt: 500}}]})
db.unicorns.find(null, {name: 1})
僅僅返回 name 這個 field,詳細例如以下所看到的:
> db.unicorns.find(null, {name: 1}){ "_id" : ObjectId("4da6f22da8d5cd3b72081cf7"), "name" : "Aurora" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cf6"), "name" : "Horny" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cf8"), "name" : "Unicrom" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cf9"), "name" : "Roooooodles" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cfa"), "name" : "Solnara" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cfb"), "name" : "Ayna" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cfc"), "name" : "Kenny" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cfd"), "name" : "Raleigh" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cfe"), "name" : "Leia" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cff"), "name" : "Pilot" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081d00"), "name" : "Nimue" }{ "_id" : ObjectId("4da6f231a8d5cd3b72081d01"), "name" : "Dunx" }> db.unicorns.find(null, {name: 1,_id:0}){ "name" : "Aurora" }{ "name" : "Horny" }{ "name" : "Unicrom" }{ "name" : "Roooooodles" }{ "name" : "Solnara" }{ "name" : "Ayna" }{ "name" : "Kenny" }{ "name" : "Raleigh" }{ "name" : "Leia" }{ "name" : "Pilot" }{ "name" : "Nimue" }{ "name" : "Dunx" }
sort
db.unicorns.find().sort({weight: -1})db.unicorns.find().sort({name: 1, vampires: -1})#1 表示升序,-1 表示降序db.unicorns.find().sort({weight: -1}).limit(2).skip(1)#得到第二個和第三個,limit 規定查詢個數,skip 規定忽略幾個。
count
db.unicorns.count({vampires: {$gt: 50}})#ordb.unicorns.find({vampires: {$gt: 50}}).count()
remove
db.unicorns.remove()如以下所看到的。> db.unicorns.remove()> db.unicorns.find()>
update
db.unicorns.update({name: ‘jingdong‘}, {weight: 590})
注意:此語句運行後,先查詢 name 是‘jingdong‘的全部資料,然後將 name是‘jingdong‘的整個 document 都替換為{weight: 590}。
即 db.unicorns.insert({name: ‘jingdong‘, dob: new Date(1979, 7, 18, 18, 44),loves:[‘apple‘], weight: 575, gender: ‘m‘, vampires: 99});整個替換為{weight: 590},最後僅僅剩一個{weight: 590}。
運行$set,不會替換原有資料,因此正確的更新方式例如以下:
db.unicorns.update({name: ‘jingdong‘}, {$set: {weight: 590}})
db.unicorns.update({name: ‘Pilot‘}, {$inc: {<span style="font-size:14px;">weight: 500</span>}})$inc 添加或降低數字 假設原來為500之後會變為1000,由於500+500 = 1000db.unicorns.update({name: ‘Aurora‘}, {$push: {loves: ‘sugar‘}})$push 添加數組元素$pop 降低數組元素
若存在則更新,否則加入db.hits.update({page: ‘unicorns‘}, {$inc: {hits: 1}}, true);db.hits.find();使用第三個參數設定是否 true(upset),預設是 false
#批次更新db.unicorns.update({}, {$set: {vaccinated: true }});db.unicorns.find({vaccinated: true});不會將全部的資料的 vaccinated 都更新為 true若將全部的資料的 vaccinated 都更新為 true,則例如以下:db.unicorns.update({}, {$set: {vaccinated: true }}, false, true);db.unicorns.find({vaccinated: true});
ensureIndex
建立索引的方式
db.unicorns.ensureIndex({name: 1})
刪除索引的方式
db.unicorns.dropIndex({name: 1})
建立獨立索引
db.unicorns.ensureIndex({name: 1}, {unique: true})
建立聯合索引
db.unicorns.dropIndex({name: 1, vampires: -1})
使用 web 獲得 mongoDB 的資訊
使用 http://localhost:28017/ 獲得 MongoDB 的資訊。
資料備份和恢複
使用 mongodump備份資料庫
mongodump
使用 mongorestore恢複資料庫
mongorestore
MongoDB經常使用命令