Explore o novo chatbot do Developer Center! O MongoDB AI chatbot pode ser acessado na parte superior da sua navegação para responder a todas as suas perguntas sobre o MongoDB .

Desenvolvedor do MongoDB
Central de desenvolvedor do MongoDBchevron-right
Produtoschevron-right
MongoDBchevron-right

Folha de referências do MongoDB

Maxime Beugnet5 min read • Published Jan 31, 2022 • Updated Sep 29, 2023
MongoDB
Ícone do FacebookÍcone do Twitterícone do linkedin
Avalie esse Início rápido
star-empty
star-empty
star-empty
star-empty
star-empty
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!
  • Obtenha um MongoDB cluster gratuito no MongoDB Atlas.
  • Faça um curso na MongoDB University.

Atualizações

  • setembro de 2023: atualizado para o MongoDB 7.0.

Sumário

Conecte-se via

mongosh
1mongosh # connects to mongodb://127.0.0.1:27017 by default
2mongosh --host <host> --port <port> --authenticationDatabase admin -u <user> -p <pwd> # omit the password if you want a prompt
3mongosh "mongodb://<user>:<password>@192.168.1.1:27017"
4mongosh "mongodb://192.168.1.1:27017"
5mongosh "mongodb+srv://cluster-name.abcde.mongodb.net/<dbname>" --apiVersion 1 --username <username> # MongoDB Atlas
🔝 Índice 🔝

Auxiliares

Mostrar bancos de dados

1show dbs
2db // prints the current database

Trocar banco de dados

1use <database_name>

Mostrar coleções

1show collections

Executar um arquivo JavaScript

1load("myScript.js")
🔝 Índice 🔝

CRUD

criar

1db.coll.insertOne({name: "Max"})
2db.coll.insertMany([{name: "Max"}, {name:"Alex"}]) // ordered bulk insert
3db.coll.insertMany([{name: "Max"}, {name:"Alex"}], {ordered: false}) // unordered bulk insert
4db.coll.insertOne({date: ISODate()})
5db.coll.insertOne({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})

Leia

1db.coll.findOne() // returns a single document
2db.coll.find() // returns a cursor - show 20 results - "it" to display more
3db.coll.find().pretty()
4db.coll.find({name: "Max", age: 32}) // implicit logical "AND".
5db.coll.find({date: ISODate("2020-09-25T13:57:17.180Z")})
6db.coll.find({name: "Max", age: 32}).explain("executionStats") // or "queryPlanner" or "allPlansExecution"
7db.coll.distinct("name")
8
9// Count
10db.coll.countDocuments({age: 32}) // alias for an aggregation pipeline - accurate count
11db.coll.estimatedDocumentCount() // estimation based on collection metadata
12
13// Comparison
14db.coll.find({"year": {$gt: 1970}})
15db.coll.find({"year": {$gte: 1970}})
16db.coll.find({"year": {$lt: 1970}})
17db.coll.find({"year": {$lte: 1970}})
18db.coll.find({"year": {$ne: 1970}})
19db.coll.find({"year": {$in: [1958, 1959]}})
20db.coll.find({"year": {$nin: [1958, 1959]}})
21
22// Logical
23db.coll.find({name:{$not: {$eq: "Max"}}})
24db.coll.find({$or: [{"year" : 1958}, {"year" : 1959}]})
25db.coll.find({$nor: [{price: 1.99}, {sale: true}]})
26db.coll.find({
27 $and: [
28 {$or: [{qty: {$lt :10}}, {qty :{$gt: 50}}]},
29 {$or: [{sale: true}, {price: {$lt: 5 }}]}
30 ]
31})
32
33// Element
34db.coll.find({name: {$exists: true}})
35db.coll.find({"zipCode": {$type: 2 }})
36db.coll.find({"zipCode": {$type: "string"}})
37
38// Aggregation Pipeline
39db.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
46db.coll.find({$text: {$search: "cake"}}, {score: {$meta: "textScore"}}).sort({score: {$meta: "textScore"}})
47
48// Regex
49db.coll.find({name: /^Max/}) // regex: starts by letter "M"
50db.coll.find({name: /^Max$/i}) // regex case insensitive
51
52// Array
53db.coll.find({tags: {$all: ["Realm", "Charts"]}})
54db.coll.find({field: {$size: 2}}) // impossible to index - prefer storing the size of the array & update it
55db.coll.find({results: {$elemMatch: {product: "xyz", score: {$gte: 8}}}})
56
57// Projections
58db.coll.find({"x": 1}, {"actors": 1}) // actors + _id
59db.coll.find({"x": 1}, {"actors": 1, "_id": 0}) // actors
60db.coll.find({"x": 1}, {"actors": 0, "summary": 0}) // all but "actors" and "summary"
61
62// Sort, skip, limit
63db.coll.find({}).sort({"year": 1, "rating": -1}).skip(10).limit(3)
64
65// Read Concern
66db.coll.find().readConcern("majority")

Atualização

1db.coll.updateOne({"_id": 1}, {$set: {"year": 2016, name: "Max"}})
2db.coll.updateOne({"_id": 1}, {$unset: {"year": 1}})
3db.coll.updateOne({"_id": 1}, {$rename: {"year": "date"} })
4db.coll.updateOne({"_id": 1}, {$inc: {"year": 5}})
5db.coll.updateOne({"_id": 1}, {$mul: {price: NumberDecimal("1.25"), qty: 2}})
6db.coll.updateOne({"_id": 1}, {$min: {"imdb": 5}})
7db.coll.updateOne({"_id": 1}, {$max: {"imdb": 8}})
8db.coll.updateOne({"_id": 1}, {$currentDate: {"lastModified": true}})
9db.coll.updateOne({"_id": 1}, {$currentDate: {"lastModified": {$type: "timestamp"}}})
10
11// Array
12db.coll.updateOne({"_id": 1}, {$push :{"array": 1}})
13db.coll.updateOne({"_id": 1}, {$pull :{"array": 1}})
14db.coll.updateOne({"_id": 1}, {$addToSet :{"array": 2}})
15db.coll.updateOne({"_id": 1}, {$pop: {"array": 1}}) // last element
16db.coll.updateOne({"_id": 1}, {$pop: {"array": -1}}) // first element
17db.coll.updateOne({"_id": 1}, {$pullAll: {"array" :[3, 4, 5]}})
18db.coll.updateOne({"_id": 1}, {$push: {"scores": {$each: [90, 92]}}})
19db.coll.updateOne({"_id": 2}, {$push: {"scores": {$each: [40, 60], $sort: 1}}}) // array sorted
20db.coll.updateOne({"_id": 1, "grades": 80}, {$set: {"grades.$": 82}})
21db.coll.updateMany({}, {$inc: {"grades.$[]": 10}})
22db.coll.updateMany({}, {$set: {"grades.$[element]": 100}}, {multi: true, arrayFilters: [{"element": {$gte: 100}}]})
23
24// FindOneAndUpdate
25db.coll.findOneAndUpdate({"name": "Max"}, {$inc: {"points": 5}}, {returnNewDocument: true})
26
27// Upsert
28db.coll.updateOne({"_id": 1}, {$set: {item: "apple"}, $setOnInsert: {defaultQty: 100}}, {upsert: true})
29
30// Replace
31db.coll.replaceOne({"name": "Max"}, {"firstname": "Maxime", "surname": "Beugnet"})
32
33// Write concern
34db.coll.updateMany({}, {$set: {"x": 1}}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})

Excluir

1db.coll.deleteOne({name: "Max"})
2db.coll.deleteMany({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
3db.coll.deleteMany({}) // WARNING! Deletes all the docs but not the collection itself and its index definitions
4db.coll.findOneAndDelete({"name": "Max"})
🔝 Índice 🔝

Bancos de dados e coleções

descartar

1db.coll.drop() // removes the collection and its index definitions
2db.dropDatabase() // double check that you are *NOT* on the PROD cluster... :-)

criar coleção

1// Create collection with a $jsonschema
2db.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})

Outras funções de coleção

1db.coll.stats()
2db.coll.storageSize()
3db.coll.totalIndexSize()
4db.coll.totalSize()
5db.coll.validate({full: true})
6db.coll.renameCollection("new_coll", true) // 2nd parameter to drop the target collection if exists
🔝 Índice 🔝

Índices

Listar índices

1db.coll.getIndexes()
2db.coll.getIndexKeys()

Crie índices

1// Index Types
2db.coll.createIndex({"name": 1}) // single field index
3db.coll.createIndex({"name": 1, "date": 1}) // compound index
4db.coll.createIndex({foo: "text", bar: "text"}) // text index
5db.coll.createIndex({"$**": "text"}) // wildcard text index
6db.coll.createIndex({"userMetadata.$**": 1}) // wildcard index
7db.coll.createIndex({"loc": "2d"}) // 2d index
8db.coll.createIndex({"loc": "2dsphere"}) // 2dsphere index
9db.coll.createIndex({"_id": "hashed"}) // hashed index
10
11// Index Options
12db.coll.createIndex({"lastModifiedDate": 1}, {expireAfterSeconds: 3600}) // TTL index
13db.coll.createIndex({"name": 1}, {unique: true})
14db.coll.createIndex({"name": 1}, {partialFilterExpression: {age: {$gt: 18}}}) // partial index
15db.coll.createIndex({"name": 1}, {collation: {locale: 'en', strength: 1}}) // case insensitive index with strength = 1 or 2
16db.coll.createIndex({"name": 1 }, {sparse: true})

Índice de descarte

1db.coll.dropIndex("name_1")

Ocultar/Exibir índices

1db.coll.hideIndex("name_1")
2db.coll.unhideIndex("name_1")
🔝 Índice 🔝

Comandos úteis

1use admin
2db.createUser({"user": "root", "pwd": passwordPrompt(), "roles": ["root"]})
3db.dropUser("root")
4db.auth( "user", passwordPrompt() )
5
6use test
7db.getSiblingDB("dbname")
8db.currentOp()
9db.killOp(123) // opid
10
11db.fsyncLock()
12db.fsyncUnlock()
13
14db.getCollectionNames()
15db.getCollectionInfos()
16db.printCollectionStats()
17db.stats()
18
19db.getReplicationInfo()
20db.printReplicationInfo()
21db.hello()
22db.hostInfo()
23
24db.shutdownServer()
25db.serverStatus()
26
27db.getProfilingStatus()
28db.setProfilingLevel(1, 200) // 0 == OFF, 1 == ON with slowms, 2 == ON
29
30db.enableFreeMonitoring()
31db.disableFreeMonitoring()
32db.getFreeMonitoringStatus()
33
34db.createView("viewName", "sourceColl", [{$project:{department: 1}}])
🔝 Índice 🔝

Fluxos de alterações

1watchCursor = db.coll.watch( [ { $match : {"operationType" : "insert" } } ] )
2
3while (!watchCursor.isExhausted()){
4 if (watchCursor.hasNext()){
5 print(tojson(watchCursor.next()));
6 }
7}
🔝 Índice 🔝

Conjunto de réplicas

1rs.status()
2rs.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})
8rs.add("mongodb4.net:27017")
9rs.addArb("mongodb5.net:27017")
10rs.remove("mongodb1.net:27017")
11rs.conf()
12rs.hello()
13rs.printReplicationInfo()
14rs.printSecondaryReplicationInfo()
15rs.reconfig(config)
16rs.reconfigForPSASet(memberIndex, config, { options } )
17db.getMongo().setReadPref('secondaryPreferred')
18rs.stepDown(20, 5) // (stepDownSecs, secondaryCatchUpPeriodSecs)
🔝 Índice 🔝

Cluster fragmentado

1db.printShardingStatus()
2
3sh.status()
4sh.addShard("rs1/mongodb1.example.net:27017")
5sh.shardCollection("mydb.coll", {zipcode: 1})
6
7sh.moveChunk("mydb.coll", { zipcode: "53187" }, "shard0019")
8sh.splitAt("mydb.coll", {x: 70})
9sh.splitFind("mydb.coll", {x: 70})
10
11sh.startBalancer()
12sh.stopBalancer()
13sh.disableBalancing("mydb.coll")
14sh.enableBalancing("mydb.coll")
15sh.getBalancerState()
16sh.setBalancerState(true/false)
17sh.isBalancerRunning()
18
19sh.startAutoMerger()
20sh.stopAutoMerger()
21sh.enableAutoMerger()
22sh.disableAutoMerger()
23
24sh.updateZoneKeyRange("mydb.coll", {state: "NY", zip: MinKey }, { state: "NY", zip: MaxKey }, "NY")
25sh.removeRangeFromZone("mydb.coll", {state: "NY", zip: MinKey }, { state: "NY", zip: MaxKey })
26sh.addShardToZone("shard0000", "NYC")
27sh.removeShardFromZone("shard0000", "NYC")
🔝 Índice 🔝

Resumo

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.
🔝 Índice 🔝

Ícone do FacebookÍcone do Twitterícone do linkedin
Avalie esse Início rápido
star-empty
star-empty
star-empty
star-empty
star-empty
Relacionado
Artigo

Criando um aplicativo Flask e MongoDB com aplicativos de contêiner do Azure


Apr 02, 2024 | 8 min read
Artigo

O custo de não conhecer o MongoDB


Nov 11, 2024 | 23 min read
Início rápido

Criar, ler, atualizar e excluir documentos MongoDB com PHP


Sep 11, 2024 | 8 min read
Início rápido

Introdução ao MongoDB e FastAPI


Jul 12, 2024 | 7 min read
Sumário