MongoDB provides several ways to manipulate data:
- mongo / mongosh: CLI
- Compass: GUI
This document focuses on the usage of CLI.
brew install mongodb-community
To start MongoDB:
brew services start mongodb/brew/mongodb-community
or, for short,
brew services start mongodb-community
To stop MongoDB:
brew services stop mongodb-community
To restart MongoDB:
brew services restart mongodb-community
-
Launch CLI: MongoDB Legacy Shell or MongoDB Shell.
-
MongoDB Legacy Shell (deprecated in MongoDB v5.0):
mongodb
-
MongoDB Shell (introduced in MongoDB v4.0):
mongosh
-
-
Display the database being used.
db
-
Show all database instances.
show dbs
-
Switch to a database instance.
use examples
-
To create a new database, first switch to a non-exist database and then insert a document.
use products db.products.insertOne({ name: 'Beautiful Wardrobe', description: 'This is a beautiful wardrobe that you shouldn\'t miss!', brand: 'Wonderful', category: 'Wardrobe', likes: 4, tags: ['wardrobe', 'bedroom'], size: { depth: '150', height: '180', width: '200', unit: 'cm' }, date: Date() })
-
Insert many documents.
db.products.insertMany([ { name: 'Beautiful Bed Frame (Double)', description: 'This is a beautiful wardrobe that you should never miss!', brand: 'Wonderful', category: 'Bed Frame', tags: ['bed frame', 'bedroom'], size: { height: '1\'', length: '6\'3', width: '4\'6' }, date: Date() }, { name: 'Wonderful Bed Frame (Single)', description: 'This bed frame is really wonderful!!!', brand: 'Wonderful', category: 'Bed Frame', tags: ['bed frame', 'bedroom'], size: { height: '1\'', length: '6\'3', width: '3\'' }, date: Date() }, { name: '3-seats Sofa', description: 'Comfortable sofa', brand: 'Wonderful', category: 'Sofa', tags: ['sofa', 'living room'], size: { height: '100', length: '200', width: '60', unit: 'cm' }, date: Date() } ])
-
Find all documents.
db.products.find()
-
Find by criteria.
db.products.find({ category: 'Wardrobe' })
- To print pretty in legacy Mongo shell
db.products.find({ brand: 'Wonderful' }).pretty()
-
Find by limiting number of documents returned.
db.products.find().limit(2)
-
Find only one document.
db.products.findOne({ category: 'Wardrobe' })
-
Find by descending order.
db.products.find().sort({ category: -1 }).limit(2)
-
Print documents.
db.products.find().forEach(function(doc) { print('Product Name: ' + doc.name) })
-
Update single document, even if more than one document is found.
db.products.update( { name: 'Beautiful Bed Frame (Double)' }, { $set: { date: Date(), likes: 3 } }, { upsert: true } )
-
Update all matched documents.
db.products.updateMany( { brand: 'Wonderful' }, { $set: { brand: 'Wonderful', date: Date() }, $unset: { likes: 4 } } )