Mongoose Cheat Sheet

August 12, 2022
 
Common Mongoose Basics

Backup/Restore using JSON

 

Export to JSON

mongoexport --collection=krakens --db=code-gorilla --out=20220812-krakens.json --pretty
 

Import from JSON

mongoimport --collection=krakens --db=code-gorilla --file=20220812-krakens.json --type=json


Mac OS Install

 
To install mongoose on your mac:
brew tap mongodb/brew
brew update
brew install mongodb-community@6.0
 

Queries

 

Document Count

db.krakens.countDocuments()
 

Select All

db.krakens.find({})
 

Select All, ORDER BY Ascending

db.krakens.find({}).sort({'fieldName': 1})
 

Select All, ORDER BY Descending

db.krakens.find({}).sort({'fieldName': -1})
 

Find Exact Match on Field

db.krakens.find({ isValidated: false })
 

Find Exact Match on Id

db.krakens.find('_id': ObjectId('696901313fa123dc02d77777'))
 

String Partial Match (*like%), Case Sensitive

db.krakens.find({ "fieldName": { "$regex": "VegJutsu" } })
 

String Partial Match (*like%), Case Insensitive

db.krakens.find({ "fieldName": { "$regex": "VegJutsu", "$options": "i" } })
 

String Partial Match (*like%), Special Character (Parenthesis)

db.krakens.find({ "fieldName": { "$regex": "\\(" } }) })
 

Mac Start

 

macOS Service

To run MongoDB (i.e. the mongod process) as a macOS service, run:
brew services start mongodb-community@6.0
To stop a mongod running as a macOS service, use the following command as needed:
brew services stop mongodb-community@6.0
 

Automatic

To start mongodb/brew/mongodb-community now and restart at login:
brew services start mongodb/brew/mongodb-community
 

Manual

Or, if you don't want/need a background service you can just run:
M1 Processor: mongod --config /opt/homebrew/etc/mongod.conf --fork
Intel Processor: mongod --config /usr/local/etc/mongod.conf --fork
 

GUI for MongoDB

You could use Compass from MongoDB, which I tried to like:
https://www.mongodb.com/products/compass
 
But I prefer Studio 3T:
https://studio3t.com/free/
 
Note: My preference is based on what I'm familiar with and my easy of use. I'm sure the MongoDB version is awesome.
 

 
Return to articles