mongodb 数字 _id_MongoDB学习笔记MongoDB简介及数据类型
歡迎點(diǎn)擊上方藍(lán)字關(guān)注我
本文所使用的MongoDB版本為 4.0.10> db.version();4.0.10
一、MongoDB 介紹
1. MongoDB 的特點(diǎn)
MongoDB 是一個(gè)可擴(kuò)展、高性能的 NoSQL 數(shù)據(jù)庫,由 C++ 語言編寫,旨在為 web 應(yīng)用提供高性能可擴(kuò)展的數(shù)據(jù)存儲(chǔ)解決方案。
它的特點(diǎn)是高性能、易部署、易使用,存儲(chǔ)數(shù)據(jù)非常方便,主要特性有:
模式自由,支持動(dòng)態(tài)查詢、完全索引,可輕易查詢文檔中內(nèi)嵌的對象及數(shù)組。
面向集合存儲(chǔ),易存儲(chǔ)對象類型的數(shù)據(jù) , 包括文檔內(nèi)嵌對象及數(shù)組。
高效的數(shù)據(jù)存儲(chǔ) , 支持二進(jìn)制數(shù)據(jù)及大型對象 ( 如照片和視頻 )。
支持復(fù)制和故障恢復(fù);提供了 主-從、主-主模式的數(shù)據(jù)復(fù)制及服務(wù)器之間的數(shù)據(jù)復(fù)制。
自動(dòng)分片以支持云級別的伸縮性,支持水平的數(shù)據(jù)庫集群,可動(dòng)態(tài)添加額外的服務(wù)器。
2. MongoDB的優(yōu)點(diǎn)與適用場景
MongoDB的優(yōu)點(diǎn)
高性能,速度非常快(如果你的內(nèi)存足夠的話)。
沒有固定的表結(jié)構(gòu),不用為了修改表結(jié)構(gòu)而進(jìn)行數(shù)據(jù)遷移。
查詢語言簡單,容易上手。
使用Sharding實(shí)現(xiàn)水平擴(kuò)展。
部署方便。
MongoDB的適用場景
適合作為信息基礎(chǔ)設(shè)施的持久化緩存層 。
適合實(shí)時(shí)的插入,更新與查詢,并具備應(yīng)用程序?qū)崟r(shí)數(shù)據(jù)存儲(chǔ)所需的復(fù)制及高度伸縮性。
Mongo 的 BSON 數(shù)據(jù)格式非常適合文檔化格式的存儲(chǔ)及查詢。
適合由數(shù)十或數(shù)百臺(tái)服務(wù)器組成的數(shù)據(jù)庫。因?yàn)镸ongo 已經(jīng)包含了對 MapReduce 引擎的內(nèi)置支持。
二、SQL 與 NoSQL對比
MongoDB 與 Mysql 概念對應(yīng)關(guān)系
| 數(shù)據(jù)庫(datebase) | 數(shù)據(jù)庫(datebase) |
| 集合(collection) | 表(table) |
| 文檔(document) | 記錄(row) |
| 字段 | 列 / 字段 |
| 索引 | 索引 |
| 嵌入和引用 | 表內(nèi)聯(lián)結(jié) |
三、MongoDB 支持的數(shù)據(jù)類型
1. null
null用于表示空值或不存在的字段
{?"x"?:?null?}2. 布爾
布爾類型有兩個(gè)值 true 和 false
{?"x":?true?}3. 32位整數(shù)
在 Mongo Shell 中不支持這個(gè)類型。JavaScript僅支持64位浮點(diǎn)數(shù),所以32位整數(shù)會(huì)被自動(dòng)轉(zhuǎn)換為64位浮點(diǎn)數(shù)。
4. 64位整數(shù)
在 Mongo Shell 中也不支持這個(gè)類型。Mongo Shell 會(huì)使用一個(gè)特殊的內(nèi)嵌文檔來顯示64位整數(shù)。
5. 64位浮點(diǎn)數(shù)
Mongo Shell 中的數(shù)字都是這種類型。
{?"pi"?:?3.14?}JavaScript 中只有一種 “數(shù)字” 類型。因?yàn)?MongoDB 中有3種數(shù)字類型(32位整數(shù)、64位整數(shù)和64位浮點(diǎn)數(shù)), shell 必須繞過 JavaScript 的限制。默認(rèn)情況下,shell 中的數(shù)字都被 MongoDB 當(dāng)做是雙精度數(shù)。這意味著如果你從數(shù)據(jù)庫中獲得的是一個(gè)32位整數(shù),修改文檔后,將文檔存回?cái)?shù)據(jù)庫的時(shí)候,這個(gè)整數(shù)也被轉(zhuǎn)換成了浮點(diǎn)數(shù),即便保持這個(gè)整數(shù)原封不動(dòng)也會(huì)這樣的。所以明智的做法是盡量不要在 shell 下覆蓋整個(gè)文檔。數(shù)字只能表示為雙精度數(shù)(64位浮點(diǎn)數(shù))的另外一個(gè)問題是,有些64位的整數(shù)并不能精確地表示為64位浮點(diǎn)數(shù)。所以,如果存入了一個(gè)64位整數(shù),在shell中查看,它會(huì)顯示為一個(gè)內(nèi)嵌文檔。但是在數(shù)據(jù)庫中實(shí)際存儲(chǔ)的值是準(zhǔn)確的。
32位的整數(shù)都能用64位的浮點(diǎn)數(shù)精確表示,所以顯示起來沒什么特別的。
6. 字符串
UTF-8字符串都可表示為字符串類型
{?"x"?:?"abcde"?}7. 對象id
對象id使用12字節(jié)的存儲(chǔ)空間,每個(gè)字節(jié)兩位十六進(jìn)制數(shù)字,是一個(gè)24位的字符串。
{?"_id"?: ObjectId() }8. 日期
日期類型存儲(chǔ)的是亳秒級的時(shí)間戳,不存儲(chǔ)時(shí)區(qū)。
{?"d"?: new Date() }9. 正則表達(dá)式
文檔中可以包含正則表達(dá)式,采用JavaScript的正則表達(dá)式語法。
{?"x"?:?/^abc/i?}10. 代碼
文檔中可以包含JavaScript代碼
{?"x"?: function(){/********/} }11. 數(shù)組
值的集合或者列表可以表示成數(shù)組
{?"d"?: [1,2,3,4,5] }12. 內(nèi)嵌文檔
文檔中可以包含其他文檔,也可以作為值嵌入到父文檔中。
{?"x"?: {?"y"?:?"z"?} }13. undefined
文檔中也可以使用 undefined((未定義)類型(JavaScript中 null 和 undefined 是不同的類型)。
{?"a"?: undefined }14. 二進(jìn)制數(shù)據(jù)
二進(jìn)制數(shù)據(jù)可以由任意字節(jié)的串組成。可用于存儲(chǔ)圖片等二進(jìn)制文件。不過在 Mongo Shell 中無法使用。
四、Mongo Shell 幫助命令
1. 系統(tǒng)級幫助:help
> helpdb.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
# 顯示所有數(shù)據(jù)庫
show dbs show database names
# 顯示所有集合
show collections show collections in current database
# 顯示當(dāng)前數(shù)據(jù)庫所有用戶
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 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 shellexit quit the mongo shell
2. 查看數(shù)據(jù)庫上可用的操作: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
# 刪除數(shù)據(jù)庫
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
# 查看當(dāng)前數(shù)據(jù)庫中的所有集合
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,)
db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all
db.setWriteConcern() - sets the write concern for writes to the db
db.unsetWriteConcern() - 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, ) - bulk execute write operations, optional parameters are: w, wtimeout, j
# 集合中的記錄數(shù)
db.user.count( query = {}, ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
db.user.countDocuments( query = {}, ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
db.user.estimatedDocumentCount( ) - 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], )
# 集合大小
db.user.dataSize()
db.user.deleteOne( filter, ) - delete first matching document, optional parameters are: w, wtimeout, j
db.user.deleteMany( filter, ) - delete all matching documents, optional parameters are: w, wtimeout, j
db.user.distinct( key, query, ) - 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 } )
# 刪除集合內(nèi)的所有索引
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, ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS
db.user.findOneAndReplace( filter, replacement, ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
db.user.findOneAndUpdate( filter, update, ) - 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, ) - insert a document, optional parameters are: w, wtimeout, j
db.user.insertMany( [objects], ) - insert multiple documents, optional parameters are: w, wtimeout, j
db.user.mapReduce( mapFunction , reduceFunction , )
db.user.aggregate( [pipeline], ) - performs an aggregation on a collection; returns a cursor
db.user.remove(query)
db.user.replaceOne( filter, replacement, ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j
db.user.renameCollection( newName , ) renames the collection.
db.user.runCommand( name , ) 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, ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j
db.user.updateMany( filter, update, ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j
db.user.validate( ) - SLOW
db.user.getShardVersion() - only for use with sharding
db.user.getShardDistribution() - prints statistics about data distribution in the cluster
db.user.getSplitKeysForChunks( ) - 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( ) - sets the write concern for writes to the collection
db.user.unsetWriteConcern( ) - unsets the write concern for writes to the collection
db.user.latencyStats() - display operation latency histograms for this collection
點(diǎn)個(gè)在看升職加薪
總結(jié)
以上是生活随笔為你收集整理的mongodb 数字 _id_MongoDB学习笔记MongoDB简介及数据类型的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: win10系统环境变量在哪里设置(10中
- 下一篇: java获取数组穷举_请教一下两个数组各