Folha de referências do MongoDB
Avalie esse Início rápido
Primeiros passos no MongoDB World? Esta folha de dicas está repleta de dicas úteis, comandos e referências rápidas para você se conectar e "crudar" rapidamente!
- setembro de 2023: atualizado para o MongoDB 7.0.
1 mongosh # connects to mongodb://127.0.0.1:27017 by default 2 mongosh --host <host> --port <port> --authenticationDatabase admin -u <user> -p <pwd> # omit the password if you want a prompt 3 mongosh "mongodb://<user>:<password>@192.168.1.1:27017" 4 mongosh "mongodb://192.168.1.1:27017" 5 mongosh "mongodb+srv://cluster-name.abcde.mongodb.net/<dbname>" --apiVersion 1 --username <username> # MongoDB Atlas
1 show dbs 2 db // prints the current database
1 use <database_name>
1 show collections
1 load("myScript.js")
1 db.coll.insertOne({name: "Max"}) 2 db.coll.insertMany([{name: "Max"}, {name:"Alex"}]) // ordered bulk insert 3 db.coll.insertMany([{name: "Max"}, {name:"Alex"}], {ordered: false}) // unordered bulk insert 4 db.coll.insertOne({date: ISODate()}) 5 db.coll.insertOne({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
1 db.coll.findOne() // returns a single document 2 db.coll.find() // returns a cursor - show 20 results - "it" to display more 3 db.coll.find().pretty() 4 db.coll.find({name: "Max", age: 32}) // implicit logical "AND". 5 db.coll.find({date: ISODate("2020-09-25T13:57:17.180Z")}) 6 db.coll.find({name: "Max", age: 32}).explain("executionStats") // or "queryPlanner" or "allPlansExecution" 7 db.coll.distinct("name") 8 9 // Count 10 db.coll.countDocuments({age: 32}) // alias for an aggregation pipeline - accurate count 11 db.coll.estimatedDocumentCount() // estimation based on collection metadata 12 13 // Comparison 14 db.coll.find({"year": {$gt: 1970}}) 15 db.coll.find({"year": {$gte: 1970}}) 16 db.coll.find({"year": {$lt: 1970}}) 17 db.coll.find({"year": {$lte: 1970}}) 18 db.coll.find({"year": {$ne: 1970}}) 19 db.coll.find({"year": {$in: [1958, 1959]}}) 20 db.coll.find({"year": {$nin: [1958, 1959]}}) 21 22 // Logical 23 db.coll.find({name:{$not: {$eq: "Max"}}}) 24 db.coll.find({$or: [{"year" : 1958}, {"year" : 1959}]}) 25 db.coll.find({$nor: [{price: 1.99}, {sale: true}]}) 26 db.coll.find({ 27 $and: [ 28 {$or: [{qty: {$lt :10}}, {qty :{$gt: 50}}]}, 29 {$or: [{sale: true}, {price: {$lt: 5 }}]} 30 ] 31 }) 32 33 // Element 34 db.coll.find({name: {$exists: true}}) 35 db.coll.find({"zipCode": {$type: 2 }}) 36 db.coll.find({"zipCode": {$type: "string"}}) 37 38 // Aggregation Pipeline 39 db.coll.aggregate([ 40 {$match: {status: "A"}}, 41 {$group: {_id: "$cust_id", total: {$sum: "$amount"}}}, 42 {$sort: {total: -1}} 43 ]) 44 45 // Text search with a "text" index 46 db.coll.find({$text: {$search: "cake"}}, {score: {$meta: "textScore"}}).sort({score: {$meta: "textScore"}}) 47 48 // Regex 49 db.coll.find({name: /^Max/}) // regex: starts by letter "M" 50 db.coll.find({name: /^Max$/i}) // regex case insensitive 51 52 // Array 53 db.coll.find({tags: {$all: ["Realm", "Charts"]}}) 54 db.coll.find({field: {$size: 2}}) // impossible to index - prefer storing the size of the array & update it 55 db.coll.find({results: {$elemMatch: {product: "xyz", score: {$gte: 8}}}}) 56 57 // Projections 58 db.coll.find({"x": 1}, {"actors": 1}) // actors + _id 59 db.coll.find({"x": 1}, {"actors": 1, "_id": 0}) // actors 60 db.coll.find({"x": 1}, {"actors": 0, "summary": 0}) // all but "actors" and "summary" 61 62 // Sort, skip, limit 63 db.coll.find({}).sort({"year": 1, "rating": -1}).skip(10).limit(3) 64 65 // Read Concern 66 db.coll.find().readConcern("majority")
1 db.coll.updateOne({"_id": 1}, {$set: {"year": 2016, name: "Max"}}) 2 db.coll.updateOne({"_id": 1}, {$unset: {"year": 1}}) 3 db.coll.updateOne({"_id": 1}, {$rename: {"year": "date"} }) 4 db.coll.updateOne({"_id": 1}, {$inc: {"year": 5}}) 5 db.coll.updateOne({"_id": 1}, {$mul: {price: NumberDecimal("1.25"), qty: 2}}) 6 db.coll.updateOne({"_id": 1}, {$min: {"imdb": 5}}) 7 db.coll.updateOne({"_id": 1}, {$max: {"imdb": 8}}) 8 db.coll.updateOne({"_id": 1}, {$currentDate: {"lastModified": true}}) 9 db.coll.updateOne({"_id": 1}, {$currentDate: {"lastModified": {$type: "timestamp"}}}) 10 11 // Array 12 db.coll.updateOne({"_id": 1}, {$push :{"array": 1}}) 13 db.coll.updateOne({"_id": 1}, {$pull :{"array": 1}}) 14 db.coll.updateOne({"_id": 1}, {$addToSet :{"array": 2}}) 15 db.coll.updateOne({"_id": 1}, {$pop: {"array": 1}}) // last element 16 db.coll.updateOne({"_id": 1}, {$pop: {"array": -1}}) // first element 17 db.coll.updateOne({"_id": 1}, {$pullAll: {"array" :[3, 4, 5]}}) 18 db.coll.updateOne({"_id": 1}, {$push: {"scores": {$each: [90, 92]}}}) 19 db.coll.updateOne({"_id": 2}, {$push: {"scores": {$each: [40, 60], $sort: 1}}}) // array sorted 20 db.coll.updateOne({"_id": 1, "grades": 80}, {$set: {"grades.$": 82}}) 21 db.coll.updateMany({}, {$inc: {"grades.$[]": 10}}) 22 db.coll.updateMany({}, {$set: {"grades.$[element]": 100}}, {multi: true, arrayFilters: [{"element": {$gte: 100}}]}) 23 24 // FindOneAndUpdate 25 db.coll.findOneAndUpdate({"name": "Max"}, {$inc: {"points": 5}}, {returnNewDocument: true}) 26 27 // Upsert 28 db.coll.updateOne({"_id": 1}, {$set: {item: "apple"}, $setOnInsert: {defaultQty: 100}}, {upsert: true}) 29 30 // Replace 31 db.coll.replaceOne({"name": "Max"}, {"firstname": "Maxime", "surname": "Beugnet"}) 32 33 // Write concern 34 db.coll.updateMany({}, {$set: {"x": 1}}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
1 db.coll.deleteOne({name: "Max"}) 2 db.coll.deleteMany({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}}) 3 db.coll.deleteMany({}) // WARNING! Deletes all the docs but not the collection itself and its index definitions 4 db.coll.findOneAndDelete({"name": "Max"})
1 db.coll.drop() // removes the collection and its index definitions 2 db.dropDatabase() // double check that you are *NOT* on the PROD cluster... :-)
1 // Create collection with a $jsonschema 2 db.createCollection("contacts", { 3 validator: {$jsonSchema: { 4 bsonType: "object", 5 required: ["phone"], 6 properties: { 7 phone: { 8 bsonType: "string", 9 description: "must be a string and is required" 10 }, 11 email: { 12 bsonType: "string", 13 pattern: "@mongodb\.com$", 14 description: "must be a string and match the regular expression pattern" 15 }, 16 status: { 17 enum: [ "Unknown", "Incomplete" ], 18 description: "can only be one of the enum values" 19 } 20 } 21 }} 22 })
1 db.coll.stats() 2 db.coll.storageSize() 3 db.coll.totalIndexSize() 4 db.coll.totalSize() 5 db.coll.validate({full: true}) 6 db.coll.renameCollection("new_coll", true) // 2nd parameter to drop the target collection if exists
1 db.coll.getIndexes() 2 db.coll.getIndexKeys()
1 // Index Types 2 db.coll.createIndex({"name": 1}) // single field index 3 db.coll.createIndex({"name": 1, "date": 1}) // compound index 4 db.coll.createIndex({foo: "text", bar: "text"}) // text index 5 db.coll.createIndex({"$**": "text"}) // wildcard text index 6 db.coll.createIndex({"userMetadata.$**": 1}) // wildcard index 7 db.coll.createIndex({"loc": "2d"}) // 2d index 8 db.coll.createIndex({"loc": "2dsphere"}) // 2dsphere index 9 db.coll.createIndex({"_id": "hashed"}) // hashed index 10 11 // Index Options 12 db.coll.createIndex({"lastModifiedDate": 1}, {expireAfterSeconds: 3600}) // TTL index 13 db.coll.createIndex({"name": 1}, {unique: true}) 14 db.coll.createIndex({"name": 1}, {partialFilterExpression: {age: {$gt: 18}}}) // partial index 15 db.coll.createIndex({"name": 1}, {collation: {locale: 'en', strength: 1}}) // case insensitive index with strength = 1 or 2 16 db.coll.createIndex({"name": 1 }, {sparse: true})
1 db.coll.dropIndex("name_1")
1 db.coll.hideIndex("name_1") 2 db.coll.unhideIndex("name_1")
1 use admin 2 db.createUser({"user": "root", "pwd": passwordPrompt(), "roles": ["root"]}) 3 db.dropUser("root") 4 db.auth( "user", passwordPrompt() ) 5 6 use test 7 db.getSiblingDB("dbname") 8 db.currentOp() 9 db.killOp(123) // opid 10 11 db.fsyncLock() 12 db.fsyncUnlock() 13 14 db.getCollectionNames() 15 db.getCollectionInfos() 16 db.printCollectionStats() 17 db.stats() 18 19 db.getReplicationInfo() 20 db.printReplicationInfo() 21 db.hello() 22 db.hostInfo() 23 24 db.shutdownServer() 25 db.serverStatus() 26 27 db.getProfilingStatus() 28 db.setProfilingLevel(1, 200) // 0 == OFF, 1 == ON with slowms, 2 == ON 29 30 db.enableFreeMonitoring() 31 db.disableFreeMonitoring() 32 db.getFreeMonitoringStatus() 33 34 db.createView("viewName", "sourceColl", [{$project:{department: 1}}])
1 watchCursor = db.coll.watch( [ { $match : {"operationType" : "insert" } } ] ) 2 3 while (!watchCursor.isExhausted()){ 4 if (watchCursor.hasNext()){ 5 print(tojson(watchCursor.next())); 6 } 7 }
1 rs.status() 2 rs.initiate({"_id": "RS1", 3 members: [ 4 { _id: 0, host: "mongodb1.net:27017" }, 5 { _id: 1, host: "mongodb2.net:27017" }, 6 { _id: 2, host: "mongodb3.net:27017" }] 7 }) 8 rs.add("mongodb4.net:27017") 9 rs.addArb("mongodb5.net:27017") 10 rs.remove("mongodb1.net:27017") 11 rs.conf() 12 rs.hello() 13 rs.printReplicationInfo() 14 rs.printSecondaryReplicationInfo() 15 rs.reconfig(config) 16 rs.reconfigForPSASet(memberIndex, config, { options } ) 17 db.getMongo().setReadPref('secondaryPreferred') 18 rs.stepDown(20, 5) // (stepDownSecs, secondaryCatchUpPeriodSecs)
1 db.printShardingStatus() 2 3 sh.status() 4 sh.addShard("rs1/mongodb1.example.net:27017") 5 sh.shardCollection("mydb.coll", {zipcode: 1}) 6 7 sh.moveChunk("mydb.coll", { zipcode: "53187" }, "shard0019") 8 sh.splitAt("mydb.coll", {x: 70}) 9 sh.splitFind("mydb.coll", {x: 70}) 10 11 sh.startBalancer() 12 sh.stopBalancer() 13 sh.disableBalancing("mydb.coll") 14 sh.enableBalancing("mydb.coll") 15 sh.getBalancerState() 16 sh.setBalancerState(true/false) 17 sh.isBalancerRunning() 18 19 sh.startAutoMerger() 20 sh.stopAutoMerger() 21 sh.enableAutoMerger() 22 sh.disableAutoMerger() 23 24 sh.updateZoneKeyRange("mydb.coll", {state: "NY", zip: MinKey }, { state: "NY", zip: MaxKey }, "NY") 25 sh.removeRangeFromZone("mydb.coll", {state: "NY", zip: MinKey }, { state: "NY", zip: MaxKey }) 26 sh.addShardToZone("shard0000", "NYC") 27 sh.removeShardFromZone("shard0000", "NYC")
Espero que tenha gostado da minha pequena, mas esperançosamente útil, folha de dicas. É claro que essa lista não é exaustiva. Há muitos outros comandos, mas tenho certeza de que você os encontrará na documentação do MongoDB.
Se você achar que esqueci um comando importante nesta lista, envie-me um tweet e eu me certificarei de corrigi-lo.
Confira nossos cursos gratuitos na MongoDB University se você não tiver certeza do que alguns dos comandos acima estão fazendo.
Se tiver dúvidas, acesse o site da nossa comunidade de desenvolvedores, no qual os engenheiros e a comunidade do MongoDB ajudarão você a desenvolver sua próxima grande ideia com o MongoDB.