本文所使用的MongoDB版本爲 4.0.10
> db.version(); 4.0.10
MongoDB 是一個可擴展、高性能的 NoSQL 數據庫,由 C++ 語言編寫,旨在爲 web 應用提供高性能可擴展的數據存儲解決方案。
它的特色是高性能、易部署、易使用,存儲數據很是方便,主要特性有:mysql
MongoDB的優勢web
MongoDB的適用場景正則表達式
- | SQL數據庫 | NoSQL數據庫 |
---|---|---|
類型 | 全部類型都支持SQL標準 | 存在多種類型,好比文檔存儲、鍵值存儲、列數據庫等 |
示例 | MySQL、SQL Server、Oracle | MongoDB、HBase、Cassandra |
數據存儲模型 | 數據被存儲在表的行和列中,其中每一列都有一個特定類型。 表一般都是按照標準化原則建立的。 使用聯接來從多個表中檢索數據。 |
數據模型取決於數據庫類型。 好比數據被存儲爲鍵值對以用於鍵值存儲。在基於文檔的數據庫中,數據會被存儲爲文檔。 NoSQL的數據模型是靈活的,與SQL數據庫死板的表模型相反。 |
模式 | 固定的結構和模式,所以對模式的任何變動都涉及修改數據庫 | 動態模式,經過擴展或修改當前模式就能適應新的數據類型或結構。 能夠動態添加新的字段 |
可擴展性 | 使用了縱向擴展方式。這意味着隨着負荷的增長,須要購買更大、更貴的服務器來容納數據。 | 使用了橫向擴展方式。這意味着能夠將數據負荷分散到多臺廉價服務器上。 |
支持事務 | 支持ACID和事務 | 支持分區和可用性,會損害事務。 事務存在於某個級別,好比數據庫級別或文檔級別。 |
一致性 | 強一致性 | 取決於產品。有些產品選擇提供強一致性,而有些提供最終一致性。 |
查詢功能 | 可經過易用的GUI界面來使用 | 查詢可能須要編程專業技術和知識。與UI不一樣,其重心在於功能和編程接口 |
mongodb | mysql |
---|---|
數據庫(datebase) | 數據庫(datebase) |
集合(collection) | 表(table) |
文檔(document) | 記錄(row) |
字段 | 列 / 字段 |
索引 | 索引 |
嵌入和引用 | 表內聯結 |
null用於表示空值或不存在的字段sql
{ "x" : null }
布爾類型有兩個值 true 和 falsemongodb
{ "x": true }
在 Mongo Shell 中不支持這個類型。JavaScript僅支持64位浮點數,因此32位整數會被自動轉換爲64位浮點數。shell
在 Mongo Shell 中也不支持這個類型。Mongo Shell 會使用一個特殊的內嵌文檔來顯示64位整數。數據庫
Mongo Shell 中的數字都是這種類型。編程
{ "pi" : 3.14 }
JavaScript 中只有一種 「數字」 類型。由於 MongoDB 中有3種數字類型(32位整數、64位整數和64位浮點數), shell 必須繞過 JavaScript 的限制。默認狀況下,shell 中的數字都被 MongoDB 當作是雙精度數。這意味着若是你從數據庫中得到的是一個32位整數,修改文檔後,將文檔存回數據庫的時候,這個整數也被轉換成了浮點數,即使保持這個整數原封不動也會這樣的。因此明智的作法是儘可能不要在 shell 下覆蓋整個文檔。數字只能表示爲雙精度數(64位浮點數)的另一個問題是,有些64位的整數並不能精確地表示爲64位浮點數。因此,若是存入了一個64位整數,在shell中查看,它會顯示爲一個內嵌文檔。可是在數據庫中實際存儲的值是準確的。json
32位的整數都能用64位的浮點數精確表示,因此顯示起來沒什麼特別的。數組
UTF-8字符串均可表示爲字符串類型
{ "x" : "abcde" }
對象id使用12字節的存儲空間,每一個字節兩位十六進制數字,是一個24位的字符串。
{ "_id" : ObjectId() }
日期類型存儲的是亳秒級的時間戳,不存儲時區。
{ "d" : new Date() }
文檔中能夠包含正則表達式,採用JavaScript的正則表達式語法。
{ "x" : /^abc/i }
文檔中能夠包含JavaScript代碼
{ "x" : function(){/********/} }
值的集合或者列表能夠表示成數組
{ "d" : [1,2,3,4,5] }
文檔中能夠包含其餘文檔,也能夠做爲值嵌入到父文檔中。
{ "x" : { "y" : "z" } }
文檔中也可使用 undefined((未定義)類型(JavaScript中 null 和 undefined 是不一樣的類型)。
{ "a" : undefined }
二進制數據能夠由任意字節的串組成。可用於存儲圖片等二進制文件。不過在 Mongo Shell 中沒法使用。
> help db.help() help on db methods db.mycoll.help() help on collection methods sh.help() sharding helpers rs.help() replica set helpers help admin administrative help help connect connecting to a db help help keys key shortcuts help misc misc things to know help mr mapreduce # 顯示全部數據庫 show dbs show database names # 顯示全部集合 show collections show collections in current database # 顯示當前數據庫全部用戶 show users show users in current database show profile show most recent system.profile entries with time >= 1ms show logs show the accessible logger names show log [name] prints out the last segment of log in memory, 'global' is default use <db_name> set current database db.foo.find() list objects in collection foo db.foo.find( { a : 1 } ) list objects in foo where a == 1 it result of the last line evaluated; use to further iterate DBQuery.shellBatchSize = x set default number of items to display on shell exit quit the mongo shell
> db.help() DB methods: db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)] db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor db.auth(username, password) db.cloneDatabase(fromhost) - deprecated db.commandHelp(name) returns the help for the command db.copyDatabase(fromdb, todb, fromhost) - deprecated db.createCollection(name, {size: ..., capped: ..., max: ...}) db.createView(name, viewOn, [{$operator: {...}}, ...], {viewOptions}) 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.version() current version of the server
> db.user.help() DBCollection help db.user.find().help() - show DBCursor help db.user.bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j # 集合中的記錄數 db.user.count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS db.user.countDocuments( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS db.user.estimatedDocumentCount( <optional params> ) - estimate the document count using collection metadata, optional parameters are: maxTimeMS db.user.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied. db.user.convertToCapped(maxBytes) - calls {convertToCapped:'user', size:maxBytes}} command db.user.createIndex(keypattern[,options]) db.user.createIndexes([keypatterns], <options>) # 集合大小 db.user.dataSize() db.user.deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j db.user.deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j db.user.distinct( key, query, <optional params> ) - e.g. db.user.distinct( 'x' ), optional parameters are: maxTimeMS # 刪除集合 db.user.drop() drop the collection db.user.dropIndex(index) - e.g. db.user.dropIndex( "indexName" ) or db.user.dropIndex( { "indexKey" : 1 } ) # 刪除集合內的全部索引 db.user.dropIndexes() db.user.ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead db.user.explain().help() - show explain help db.user.reIndex() db.user.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return. e.g. db.user.find( {x:77} , {name:1, x:1} ) db.user.find(...).count() db.user.find(...).limit(n) db.user.find(...).skip(n) db.user.find(...).sort(...) db.user.findOne([query], [fields], [options], [readConcern]) db.user.findOneAndDelete( filter, <optional params> ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS db.user.findOneAndReplace( filter, replacement, <optional params> ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument db.user.findOneAndUpdate( filter, update, <optional params> ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument db.user.getDB() get DB object associated with collection db.user.getPlanCache() get query plan cache associated with collection db.user.getIndexes() db.user.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } ) db.user.insert(obj) db.user.insertOne( obj, <optional params> ) - insert a document, optional parameters are: w, wtimeout, j db.user.insertMany( [objects], <optional params> ) - insert multiple documents, optional parameters are: w, wtimeout, j db.user.mapReduce( mapFunction , reduceFunction , <optional params> ) db.user.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor db.user.remove(query) db.user.replaceOne( filter, replacement, <optional params> ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j db.user.renameCollection( newName , <dropTarget> ) renames the collection. db.user.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name db.user.save(obj) db.user.stats({scale: N, indexDetails: true/false, indexDetailsKey: <index key>, indexDetailsName: <index name>}) db.user.storageSize() - includes free space allocated to this collection db.user.totalIndexSize() - size in bytes of all the indexes db.user.totalSize() - storage allocated for all data and indexes db.user.update( query, object[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi db.user.updateOne( filter, update, <optional params> ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j db.user.updateMany( filter, update, <optional params> ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j db.user.validate( <full> ) - SLOW db.user.getShardVersion() - only for use with sharding db.user.getShardDistribution() - prints statistics about data distribution in the cluster db.user.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function db.user.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set db.user.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection db.user.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collection db.user.latencyStats() - display operation latency histograms for this collection