亚洲成A人片在线观看网站_成年网站免费视频A在线双飞_日日日日做夜夜夜夜无码_久久夜色撩人精品国产小说

MongoDB 備忘清單

此(ci)備忘單包含一些(xie)方便的提示(shi)、命令和快速(su)參考,可讓您立(li)即連(lian)接并進行 CRUD

入門

連接 MongoDB Shell

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

顯示數據庫

show dbs
db // 打印當前數據(ju)庫(ku)

切換數據庫

use <database_name>

顯示收藏

show collections

運行 JavaScript 文件

load("myScript.js")

CRUD

創建

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

尋找文件

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

使用運算符查找文檔

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正則表達式匹配db.docx.find({name:{$regex:'^USS\\sE'}})
$type按元素類型搜索db.docx.find({name : {$type:4}})

讀取

db.coll.findOne() // 返(fan)回(hui)單(dan)個文(wen)檔
db.coll.find()    // 返(fan)回一(yi)個游標 - 顯示 20 個結果 - "it" 顯示更多(duo)
db.coll.find().pretty()
db.coll.find({name: "Max", age: 32}) // 隱(yin)式邏輯“與(yu)”。
db.coll.find({date: ISODate("2019-09-25T13:57:17.180Z")})

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

// 數數
db.coll.count({age: 32})          // 基于(yu)館藏元數據的(de)估(gu)計
db.coll.estimatedDocumentCount()  // 基于館(guan)藏元數據的估計
db.coll.countDocuments({age: 32}) // 聚合管(guan)道(dao)的別名 - 準確計(ji)數(shu)

// 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}}
])

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

// Regex 正則表(biao)達式
db.coll.find({name: /^Max/})   // 正則表達式:以字母“M”開頭
db.coll.find({name: /^Max$/i}) // 正則表達式(shi)不(bu)區分(fen)大(da)小寫

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

// Projections 預測(ce)
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}) // 除(chu)了“actors”和“summary”之(zhi)外的所(suo)有(you)內容

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

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

更新

db.coll.update({"_id": 1}, {"year": 2016}) // 警告! 替換整個文(wen)檔
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}})  // 最(zui)后一個元素
db.coll.update({"_id": 1}, {$pop: {"array": -1}}) // 第一個元素
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}}]})

// 更(geng)新很(hen)多
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 保(bao)存
db.coll.save({"item": "book", "qty": 40})

// Write concern 寫(xie)關注
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({}) // 警告!刪除(chu)所(suo)有文檔但不刪除(chu)集(ji)合本身及其索引(yin)定義
db.coll.remove({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
db.coll.findOneAndDelete({"name": "Max"})

數據庫和集合

Drop

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

創建集合

// 使(shi)用 $jsonschema 創建集合
db.createCollection("contacts", {
   validator: {$jsonSchema: {
      bsonType: "object",
      required: ["phone"],
      properties: {
         phone: {
            bsonType: "string",
            description: "必(bi)須是一個字符(fu)串并且是必(bi)需的(de)"
         },
         email: {
            bsonType: "string",
            pattern: "@mongodb\.com$",
            description: "必須是字(zi)符(fu)串并(bing)匹配正則表達(da)式模式"
         },
         status: {
            enum: [ "Unknown", "Incomplete" ],
            description: "只能是枚(mei)舉(ju)值之(zhi)一"
         }
      }
   }}
})

其他采集功能

db.coll.stats()
db.coll.storageSize()
db.coll.totalIndexSize()
db.coll.totalSize()
db.coll.validate({full: true})
// 第(di)二個參(can)數(shu)用于刪除目標集(ji)合(如果存在)
db.coll.renameCollection("new_coll", true)

索引

列表索引

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

創建索引

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

// Index Options
db.coll.createIndex({"lastModifiedDate": 1}, {expireAfterSeconds: 3600})      // TTL指數
db.coll.createIndex({"name": 1}, {unique: true})
db.coll.createIndex({"name": 1}, {partialFilterExpression: {age: {$gt: 18}}}) // 部分索引
// 強度為(wei) 1 或 2 的不區(qu)分(fen)大小(xiao)寫的索引
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)