Skip to content

mongoDB shell

E. Lynette Rayle edited this page Oct 24, 2023 · 2 revisions

Reference: https://www.mongodb.com/developer/products/mongodb/cheat-sheet/


Install mongo shell

brew install mongosh

Access the command line

$ mongosh "CONNECTION_STRING"
globaldb [primary] test>

Type exit to exit mongosh


List commands

List databases

show dbs

Connect to database

use DATABASE_NAME

Which database is in use

db

List users

???

List collections

show collections

List columns

n/a - record is a json structure that can vary from record to record (I think)


Create & Delete commands

Create user

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

Create database

???

Delete database

db.dropDatabase()

Delete collection

db.coll.drop()

Delete user

db.dropUser("root")

Create collection

Example because there isn't a generic simple command.

// Create collection with a $jsonschema
db.createCollection("contacts", {
   validator: {$jsonSchema: {
      bsonType: "object",
      required: ["phone"],
      properties: {
         phone: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         email: {
            bsonType: "string",
            pattern: "@mongodb\.com$",
            description: "must be a string and match the regular expression pattern"
         },
         status: {
            enum: [ "Unknown", "Incomplete" ],
            description: "can only be one of the enum values"
         }
      }
   }}
})

Querying

Finding

db.COLLECTION_NAME.findOne() - returns first
db.COLLECTION_NAME.find() - returns next 20 results
db.COLLECTION_NAME.find({name: "Max", age: 32}) - all that match name=Max && age=32 (implicit logical "AND")

NOTE: COLLECTION_NAME is either a single word (e.g. curations) or a hyphenated name (e.g. ['definitions-trimmed'])

Counting

db.COLLECTION_NAME.countDocuments()
db.COLLECTION_NAME.estimatedDocumentCount()