Skip to content

Instantly share code, notes, and snippets.

@WeltonThomasFerreira
Last active August 30, 2022 09:06
Show Gist options
  • Save WeltonThomasFerreira/a40d79192fcfa05f062b59f1dcb834cc to your computer and use it in GitHub Desktop.
Save WeltonThomasFerreira/a40d79192fcfa05f062b59f1dcb834cc to your computer and use it in GitHub Desktop.
MongoDB: Basic Shell and CRUD

MongoDB

Use Mongo Shell

mongosh

Basic Commands

# show databases
show dbs
# to switch databases
use <db>
# display the current database
db
# show collections
show collections

MongoDB CRUD Operations

CRUD operations createreadupdate, and delete documents.

Create Operations

Create or insert operations add new documents to a collection. If the collection does not currently exist, insert operations will create the collection.

# inserts a new document into a collection
db.collection.insertOne(<document>)
# inserts several new documents into a collection
db.collection.insertMany([ <document 1> , <document 2>, ... ])

Read Operations

Query a collection for documents.

# performs a query on a collection or a view and returns a cursor object
db.collection.find(query, projection)
Parameter Type Description
query document Optional. Specifies selection filter using query operators.
projection document Optional. Specifies the fields to return in the documents that match the query filter.

Update Operations

Modify existing documents in a collection.

# modifies a single document in a collection
db.collection.updateOne(<filter>, <update>, options)
# modifies multiple documents in a collection
db.collection.updateMany(<filter>, <update>, options)
# replaces a single document in a collection
db.collection.replaceOne(<filter>, <replacement>, options)
Parameter Type Description
filter document The selection criteria for the update. The same query selectors as in the find() method are available.
update document or pipeline The modifications to apply.
replacement document The replacement document.

Delete Operations

Remove documents from a collection.

# deletes a single document in a collection
db.collection.deleteOne(<filter>)
# deletes multiple documents in a collection
db.collection.deleteMany(<filter>)
Parameter Type Description
filter document Specifies deletion criteria using query operators.
version: '3.9'
services:
mongo:
image: mongo:latest
container_name: mongodb
ports:
- 27017:27017
{
"name": "mongo-gist",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"compose:up": "docker-compose up --force-recreate -d",
"compose:down": "docker-compose down -v --remove-orphans -t 0",
"mongosh": "docker exec -it mongodb mongosh",
},
"keywords": [],
"author": "",
"license": "ISC"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment