MongoDB學習筆記(1)- MongoDB簡介、數據類型及幫助命令

MongoDB學習筆記(1)- MongoDB簡介及數據類型

本文所使用的MongoDB版本爲 4.0.10
> db.version();
4.0.10

一、MongoDB 介紹

1. MongoDB 的特點

MongoDB 是一個可擴展、高性能的 NoSQL 數據庫,由 C++ 語言編寫,旨在爲 web 應用提供高性能可擴展的數據存儲解決方案。
它的特點是高性能、易部署、易使用,存儲數據非常方便,主要特性有:

  • 模式自由,支持動態查詢、完全索引,可輕易查詢文檔中內嵌的對象及數組。
  • 面向集合存儲,易存儲對象類型的數據 , 包括文檔內嵌對象及數組。
  • 高效的數據存儲 , 支持二進制數據及大型對象 ( 如照片和視頻 )。
  • 支持複製和故障恢復;提供了 主-從、主-主模式的數據複製及服務器之間的數據複製。
  • 自動分片以支持雲級別的伸縮性,支持水平的數據庫集羣,可動態添加額外的服務器。

2. MongoDB的優點與適用場景

MongoDB的優點

  • 高性能,速度非常快(如果你的內存足夠的話)。
  • 沒有固定的表結構,不用爲了修改表結構而進行數據遷移。
  • 查詢語言簡單,容易上手。
  • 使用Sharding實現水平擴展。
  • 部署方便。

MongoDB的適用場景

  • 適合作爲信息基礎設施的持久化緩存層 。
  • 適合實時的插入,更新與查詢,並具備應用程序實時數據存儲所需的複製及高度伸縮性。
  • Mongo 的 BSON 數據格式非常適合文檔化格式的存儲及查詢。
  • 適合由數十或數百臺服務器組成的數據庫。因爲Mongo 已經包含了對 MapReduce 引擎的內置支持。

二、SQL 與 NoSQL對比

- SQL數據庫 NoSQL數據庫
類型 所有類型都支持SQL標準 存在多種類型,比如文檔存儲、鍵值存儲、列數據庫等
示例 MySQL、SQL Server、Oracle MongoDB、HBase、Cassandra
數據存儲模型 數據被存儲在表的行和列中,其中每一列都有一個特定類型。
表通常都是按照標準化原則創建的。
使用聯接來從多個表中檢索數據。
數據模型取決於數據庫類型。
比如數據被存儲爲鍵值對以用於鍵值存儲。在基於文檔的數據庫中,數據會被存儲爲文檔。
NoSQL的數據模型是靈活的,與SQL數據庫死板的表模型相反。
模式 固定的結構和模式,因此對模式的任何變更都涉及修改數據庫 動態模式,通過擴展或修改當前模式就能適應新的數據類型或結構。
可以動態添加新的字段
可擴展性 使用了縱向擴展方式。這意味着隨着負荷的增加,需要購買更大、更貴的服務器來容納數據。 使用了橫向擴展方式。這意味着可以將數據負荷分散到多臺廉價服務器上。
支持事務 支持ACID和事務 支持分區和可用性,會損害事務。
事務存在於某個級別,比如數據庫級別或文檔級別。
一致性 強一致性 取決於產品。有些產品選擇提供強一致性,而有些提供最終一致性。
查詢功能 可通過易用的GUI界面來使用 查詢可能需要編程專業技術和知識。與UI不同,其重心在於功能和編程接口

MongoDB 與 Mysql 概念對應關係

mongodb mysql
數據庫(datebase) 數據庫(datebase)
集合(collection) 表(table)
文檔(document) 記錄(row)
字段 列 / 字段
索引 索引
嵌入和引用 表內聯結

三、MongoDB 支持的數據類型

1. null

null用於表示空值或不存在的字段

{ "x" : null }

2. 布爾

布爾類型有兩個值 true 和 false

{ "x": true }

3. 32位整數

在 Mongo Shell 中不支持這個類型。JavaScript僅支持64位浮點數,所以32位整數會被自動轉換爲64位浮點數。

4. 64位整數

在 Mongo Shell 中也不支持這個類型。Mongo Shell 會使用一個特殊的內嵌文檔來顯示64位整數。

5. 64位浮點數

Mongo Shell 中的數字都是這種類型。

{  "pi" : 3.14 }
JavaScript 中只有一種 “數字” 類型。因爲 MongoDB 中有3種數字類型(32位整數、64位整數和64位浮點數), shell 必須繞過 JavaScript 的限制。默認情況下,shell 中的數字都被 MongoDB 當做是雙精度數。這意味着如果你從數據庫中獲得的是一個32位整數,修改文檔後,將文檔存回數據庫的時候,這個整數也被轉換成了浮點數,即便保持這個整數原封不動也會這樣的。所以明智的做法是儘量不要在 shell 下覆蓋整個文檔。

數字只能表示爲雙精度數(64位浮點數)的另外一個問題是,有些64位的整數並不能精確地表示爲64位浮點數。所以,如果存入了一個64位整數,在shell中查看,它會顯示爲一個內嵌文檔。但是在數據庫中實際存儲的值是準確的。

32位的整數都能用64位的浮點數精確表示,所以顯示起來沒什麼特別的。

6. 字符串

UTF-8字符串都可表示爲字符串類型

{ "x" : "abcde" }

7. 對象id

對象id使用12字節的存儲空間,每個字節兩位十六進制數字,是一個24位的字符串。

{ "_id" : ObjectId() }

8. 日期

日期類型存儲的是亳秒級的時間戳,不存儲時區。

{ "d" : new Date() }

9. 正則表達式

文檔中可以包含正則表達式,採用JavaScript的正則表達式語法。

{ "x" : /^abc/i }

10. 代碼

文檔中可以包含JavaScript代碼

{ "x" : function(){/********/} }

11. 數組

值的集合或者列表可以表示成數組

{ "d" : [1,2,3,4,5] }

12. 內嵌文檔

文檔中可以包含其他文檔,也可以作爲值嵌入到父文檔中。

{ "x" : { "y" : "z" } }

13. undefined

文檔中也可以使用 undefined((未定義)類型(JavaScript中 null 和 undefined 是不同的類型)。

{ "a" : undefined }

14. 二進制數據

二進制數據可以由任意字節的串組成。可用於存儲圖片等二進制文件。不過在 Mongo Shell 中無法使用。

四、Mongo Shell 幫助命令

1. 系統級幫助:help

> 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

2. 查看數據庫上可用的操作:db.help()

> 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

3. 查看集合上可用的操作:db.集合名.help()

> 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章