国产成人精品999视频&日本一区二区亚洲人妻精品&久久久精品国产99久久精&99热这里只有成人精品国产&精品国产剧情av一区二区&成人亚洲精品久久久久app&国产精品美女高潮抽搐A片

MongoDB 備忘清單

MongoDB 此備忘單包含一些方便的提示、命令和快速參考,可讓您立即連接并進(jìn)行 CRUD

入門(mén)

連接 MongoDB Shell

mongo # 默認(rèn)連接到 mongodb://127.0.0.1:27017
mongo --host <host> --port <port> -u <user> -p <pwd> # 如果需要提示,請(qǐng)省略密碼
mongo "mongodb://192.168.1.1:27017"
# MongoDB 地圖集
mongo "mongodb+srv://cluster-name.abcde.mongodb.net/<dbname>" --username <username>

顯示數(shù)據(jù)庫(kù)

show dbs
db // 打印當(dāng)前數(shù)據(jù)庫(kù)

切換數(shù)據(jù)庫(kù)

use <database_name>

顯示收藏

show collections

運(yùn)行 JavaScript 文件

load("myScript.js")

CRUD

創(chuàng)建

db.coll.insertOne({ name: "Max" })
db.coll.insert([{ name: "Max"}, {name:"Alex"}]) // 訂購(gòu)批量插入
db.coll.insert([{ name: "Max"}, {name:"Alex"}], {ordered: false}) // 無(wú)序批量插入
db.coll.insert({ date: ISODate()})
db.coll.insert({ name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})

尋找文件

CommandsDescription
db.docx.findOne()查找一個(gè)隨機(jī)文檔
db.docx.find().prettyPrint()查找所有文檔
db.docx.find({}, {name:true, _id:false})僅顯示文檔 Docx 的名稱
db.docx.find({}, {name:true, _id:false})可以在多個(gè)文件中按屬性查找一個(gè)文件

使用運(yùn)算符查找文檔

OperatorDescriptionCommands
$gt比...更棒db.docx.find({class:{$gt:'T'}
$gte大于等于db.docx.find({class:{$gt:'T'}
$lt小于db.docx.find({class:{$lt:'T'}
$lte小于等于db.docx.find({class:{$lte:'T'}
$exists屬性是否存在db.docx.find({class:{$gt:'T'}
$regex正則表達(dá)式匹配db.docx.find({name:{$regex:'^USS\\sE'}})
$type按元素類型搜索db.docx.find({name : {$type:4}})

讀取

db.coll.findOne() // 返回單個(gè)文檔
db.coll.find()    // 返回一個(gè)游標(biāo) - 顯示 20 個(gè)結(jié)果 - "it" 顯示更多
db.coll.find().pretty()
db.coll.find({name: "Max", age: 32}) // 隱式邏輯“與”。
db.coll.find({date: ISODate("2020-09-25T13:57:17.180Z")})

// 或“queryPlanner”或“allPlansExecution”
db.coll.find({name: "Max", age: 32}).explain("executionStats") 
db.coll.distinct("name")

// 數(shù)數(shù)
db.coll.count({age: 32})          // 基于館藏元數(shù)據(jù)的估計(jì)
db.coll.estimatedDocumentCount()  // 基于館藏元數(shù)據(jù)的估計(jì)
db.coll.countDocuments({age: 32}) // 聚合管道的別名 - 準(zhǔn)確計(jì)數(shù)

// Comparison 比較
db.coll.find({"year": {$gt: 1970}})
db.coll.find({"year": {$gte: 1970}})
db.coll.find({"year": {$lt: 1970}})
db.coll.find({"year": {$lte: 1970}})
db.coll.find({"year": {$ne: 1970}})
db.coll.find({"year": {$in: [1958, 1959]}})
db.coll.find({"year": {$nin: [1958, 1959]}})


// Logical 邏輯
db.coll.find({name:{$not: {$eq: "Max"}}})
db.coll.find({$or: [{"year" : 1958}, {"year" : 1959}]})
db.coll.find({$nor: [{price: 1.99}, {sale: true}]})
db.coll.find({
  $and: [
    {$or: [{qty: {$lt :10}}, {qty :{$gt: 50}}]},
    {$or: [{sale: true}, {price: {$lt: 5 }}]}
  ]
})

// Element 元素
db.coll.find({name: {$exists: true}})
db.coll.find({"zipCode": {$type: 2 }})
db.coll.find({"zipCode": {$type: "string"}})

// Aggregation Pipeline 聚合管道
db.coll.aggregate([
  {$match: {status: "A"}},
  {$group: {_id: "$cust_id", total: {$sum: "$amount"}}},
  {$sort: {total: -1}}
])

// 使用“文本”索引進(jìn)行文本搜索
db.coll.find({$text: {$search: "cake"}}, {score: {$meta: "textScore"}})
        .sort({score: {$meta: "textScore"}})

// Regex 正則表達(dá)式
db.coll.find({name: /^Max/})   // 正則表達(dá)式:以字母“M”開(kāi)頭
db.coll.find({name: /^Max$/i}) // 正則表達(dá)式不區(qū)分大小寫(xiě)

// Array
db.coll.find({tags: {$all: ["Realm", "Charts"]}})
db.coll.find({field: {$size: 2}}) // 無(wú)法索引 - 更喜歡存儲(chǔ)數(shù)組的大小并更新它
db.coll.find({results: {$elemMatch: {product: "xyz", score: {$gte: 8}}}})

// Projections 預(yù)測(cè)
db.coll.find({"x": 1}, {"actors": 1})               // actors + _id
db.coll.find({"x": 1}, {"actors": 1, "_id": 0})     // actors
db.coll.find({"x": 1}, {"actors": 0, "summary": 0}) // 除了“actors”和“summary”之外的所有內(nèi)容

// Sort 排序, skip 跳過(guò), limit 限制
db.coll.find({}).sort({"year": 1, "rating": -1}).skip(10).limit(3)

// Read Concern 閱讀關(guān)注
db.coll.find().readConcern("majority")

更新

db.coll.update({"_id": 1}, {"year": 2016}) // 警告! 替換整個(gè)文檔
db.coll.update({"_id": 1}, {$set: {"year": 2016, name: "Max"}})
db.coll.update({"_id": 1}, {$unset: {"year": 1}})
db.coll.update({"_id": 1}, {$rename: {"year": "date"} })
db.coll.update({"_id": 1}, {$inc: {"year": 5}})
db.coll.update({"_id": 1}, {$mul: {price: NumberDecimal("1.25"), qty: 2}})
db.coll.update({"_id": 1}, {$min: {"imdb": 5}})
db.coll.update({"_id": 1}, {$max: {"imdb": 8}})
db.coll.update({"_id": 1}, {$currentDate: {"lastModified": true}})
db.coll.update({"_id": 1}, {$currentDate: {"lastModified": {$type: "timestamp"}}})

// Array
db.coll.update({"_id": 1}, {$push :{"array": 1}})
db.coll.update({"_id": 1}, {$pull :{"array": 1}})
db.coll.update({"_id": 1}, {$addToSet :{"array": 2}})
db.coll.update({"_id": 1}, {$pop: {"array": 1}})  // 最后一個(gè)元素
db.coll.update({"_id": 1}, {$pop: {"array": -1}}) // 第一個(gè)元素
db.coll.update({"_id": 1}, {$pullAll: {"array" :[3, 4, 5]}})
db.coll.update({"_id": 1}, {$push: {scores: {$each: [90, 92, 85]}}})
db.coll.updateOne({"_id": 1, "grades": 80}, {$set: {"grades.$": 82}})
db.coll.updateMany({}, {$inc: {"grades.$[]": 10}})
db.coll.update({}, {$set: {"grades.$[element]": 100}}, {multi: true, arrayFilters: [{"element": {$gte: 100}}]})

// 更新很多
db.coll.update({"year": 1999}, {$set: {"decade": "90's"}}, {"multi":true})
db.coll.updateMany({"year": 1999}, {$set: {"decade": "90's"}})

// FindOneAndUpdate 查找并更新
db.coll.findOneAndUpdate({"name": "Max"}, {$inc: {"points": 5}}, {returnNewDocument: true})

// Upsert 更新插入
db.coll.update({"_id": 1}, {$set: {item: "apple"}, $setOnInsert: {defaultQty: 100}}, {upsert: true})

// Replace 代替
db.coll.replaceOne({"name": "Max"}, {"firstname": "Maxime", "surname": "Beugnet"})

// Save 保存
db.coll.save({"item": "book", "qty": 40})

// Write concern 寫(xiě)關(guān)注
db.coll.update({}, {$set: {"x": 1}}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})

刪除

db.coll.remove({name: "Max"})
db.coll.remove({name: "Max"}, {justOne: true})
db.coll.remove({}) // 警告!刪除所有文檔但不刪除集合本身及其索引定義
db.coll.remove({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
db.coll.findOneAndDelete({"name": "Max"})

數(shù)據(jù)庫(kù)和集合

Drop

// 刪除集合及其索引定義
db.coll.drop()    
// 仔細(xì)檢查你*不*在 PROD 集群上......:-)
db.dropDatabase() 

創(chuàng)建集合

// 使用 $jsonschema 創(chuàng)建集合
db.createCollection("contacts", {
   validator: {$jsonSchema: {
      bsonType: "object",
      required: ["phone"],
      properties: {
         phone: {
            bsonType: "string",
            description: "必須是一個(gè)字符串并且是必需的"
         },
         email: {
            bsonType: "string",
            pattern: "@mongodb\.com$",
            description: "必須是字符串并匹配正則表達(dá)式模式"
         },
         status: {
            enum: [ "Unknown", "Incomplete" ],
            description: "只能是枚舉值之一"
         }
      }
   }}
})

其他采集功能

db.coll.stats()
db.coll.storageSize()
db.coll.totalIndexSize()
db.coll.totalSize()
db.coll.validate({full: true})
// 第二個(gè)參數(shù)用于刪除目標(biāo)集合(如果存在)
db.coll.renameCollection("new_coll", true)

索引

列表索引

db.coll.getIndexes()
db.coll.getIndexKeys()

創(chuàng)建索引

// 索引類型
db.coll.createIndex({"name": 1})                // 單字段索引
db.coll.createIndex({"name": 1, "date": 1})     // 復(fù)合索引
db.coll.createIndex({foo: "text", bar: "text"}) // 文本索引
db.coll.createIndex({"$**": "text"})            // 通配符文本索引
db.coll.createIndex({"userMetadata.$**": 1})    // 通配符索引
db.coll.createIndex({"loc": "2d"})              // 二維索引
db.coll.createIndex({"loc": "2dsphere"})        // 2dsphere 索引
db.coll.createIndex({"_id": "hashed"})          // 哈希索引

// Index Options
db.coll.createIndex({"lastModifiedDate": 1}, {expireAfterSeconds: 3600})      // TTL指數(shù)
db.coll.createIndex({"name": 1}, {unique: true})
db.coll.createIndex({"name": 1}, {partialFilterExpression: {age: {$gt: 18}}}) // 部分索引
// 強(qiáng)度為 1 或 2 的不區(qū)分大小寫(xiě)的索引
db.coll.createIndex({"name": 1}, {collation: {locale: 'en', strength: 1}})
db.coll.createIndex({"name": 1 }, {sparse: true})

刪除索引

db.coll.dropIndex("name_1")

隱藏/取消隱藏索引

db.coll.hideIndex("name_1")
db.coll.unhideIndex("name_1")

方便的命令

use admin
db.createUser({"user": "root", "pwd": passwordPrompt(), "roles": ["root"]})
db.dropUser("root")
db.auth( "user", passwordPrompt() )

use test
db.getSiblingDB("dbname")
db.currentOp()
db.killOp(123) // opid

db.fsyncLock()
db.fsyncUnlock()

db.getCollectionNames()
db.getCollectionInfos()
db.printCollectionStats()
db.stats()

db.getReplicationInfo()
db.printReplicationInfo()
db.isMaster()
db.hostInfo()
db.printShardingStatus()
db.shutdownServer()
db.serverStatus()

db.setSlaveOk()
db.getSlaveOk()

db.getProfilingLevel()
db.getProfilingStatus()
db.setProfilingLevel(1, 200) // 0 == OFF, 1 == ON with slowms, 2 == ON

db.enableFreeMonitoring()
db.disableFreeMonitoring()
db.getFreeMonitoringStatus()

db.createView("viewName", "sourceColl", [{$project:{department: 1}}])

各種各樣的

改變流

watchCursor = db.coll.watch([
   {
      $match : {"operationType": "insert" }
   }
])

while (!watchCursor.isExhausted()){
   if (watchCursor.hasNext()){
      print(tojson(watchCursor.next()));
   }
}

分片集群

sh.status()
sh.addShard("rs1/mongodbd1.example.net:27017")
sh.shardCollection("mydb.coll", {zipcode: 1})

sh.moveChunk("mydb.coll", { zipcode: "53187" }, "shard0019")
sh.splitAt("mydb.coll", {x: 70})
sh.splitFind("mydb.coll", {x: 70})
sh.disableAutoSplit()
sh.enableAutoSplit()

sh.startBalancer()
sh.stopBalancer()
sh.disableBalancing("mydb.coll")
sh.enableBalancing("mydb.coll")
sh.getBalancerState()
sh.setBalancerState(true/false)
sh.isBalancerRunning()

sh.addTagRange("mydb.coll", {state: "NY",zip: MinKey}, {state: "NY",zip: MaxKey}, "NY")
sh.removeTagRange("mydb.coll", {state: "NY",zip: MinKey}, {state: "NY",zip: MaxKey}, "NY")
sh.addShardTag("shard0000", "NYC")
sh.removeShardTag("shard0000", "NYC")

sh.addShardToZone("shard0000", "JFK")
sh.removeShardFromZone("shard0000", "NYC")
sh.removeRangeFromZone("mydb.coll", {a: 1, b: 1}, {a: 10, b: 10})

副本集

rs.status()
rs.initiate({"_id": "replicaTest",
  members: [
    { _id: 0, host: "127.0.0.1:27017" },
    { _id: 1, host: "127.0.0.1:27018" },
    { _id: 2, host: "127.0.0.1:27019",
    arbiterOnly:true }]
})
rs.add("mongodbd1.example.net:27017")
rs.addArb("mongodbd2.example.net:27017")
rs.remove("mongodbd1.example.net:27017")
rs.conf()
rs.isMaster()
rs.printReplicationInfo()
rs.printSlaveReplicationInfo()
rs.reconfig(<valid_conf>)
rs.slaveOk()
rs.stepDown(20, 5)
// (stepDownSecs, secondaryCatchUpPeriodSecs)