- Fire up MongoDB (or check that it's running)
MacOS:
brew services status mongodb/brew/mongodb-community
to check status > ORbrew services restart mongodb/brew/mongodb-communit
to start/restart
- Get into the MongoDB Shell:
mongo <database-name>
( is optional)
$ mongo mongo-crud
MongoDB shell version v4.2.0
connecting to: mongodb://127.0.0.1:27017/mongo-crud?compressors=disabled&gssapiServiceName=mongodb
- Display current database:
db
- See all databases:
show databases
ORshow dbs
- Switch databases:
use <database-name>
- See all the collections in a database:
show collections
-
Find all documents in a collection:
db.collectionName.find()
- If my collection name is
people
:db.people.find()
- Pretty print:
db.people.find().pretty()
- If my collection name is
-
Find all item(s) that match a certain field/value pair in a collection:
db.collectionName.find({ field: 'search/desired value' })
-
Find the first match for a query in a collection:
db.collectionName.findOne({ field: 'wanted value' })
- Use
/partial value/
instead of'wanted value'
to find all values containing the partial value eg.db.collectionName.find({ family_name: /Rod/ })
returns 'Rodriguez' and 'Rodgers'
- Use
-
Find the number of matches of a given query:
db.collectionName.find({ field: 'wanted value' }).count()
-
Sort query:
db.collectionName.find(<query>).sort({ field: -1 })
(-1 is descending, 1 is ascending) -
Limit query:
db.collectionName.find(<query>).limit(3)
will gave back only 3 or fewer matches -
*DANGER: * Drop the whole database:
db.dropDatabase()
-
*DANGER: * Drop the whole collection:
db.collectionName.drop()
-
Delete ONE item from a collection:
db.collection.deleteOne(<query>)
ORdb.collectionName.remove({<query>, true})
-
Delete ALL items from a collection:
db.collectionName.deleteMany({})
ORdb.collectionName.remove({})
-
Delete ALL MATCHES of a query from a collection:
db.collectionName.deleteMany(<query>)
ORdb.collectionName.remove(<query>)
- To add/update/set fields:
db.collectionName.update(<query>, { set: <update-object> }, <options>)
- To remove fields:
db.collectionName.update(<query>, { $unset: <field-match-query> }, options)
- Pass
{multi: true }
as<options>
to update multiple matches
- Pass
db.collectionName.updateMany(<query>, { $set: <update-object> }, <options>)
db.collectionName.updateOne(<query>, { $set: <update-object> }, <options>)
db.collectionName.replaceOne(<query>, { $set: <update-object> }, <options>)
- To insert one:
db.collectionName.insertOne(<document-object>)
- To insert many:
db.collectionName.insertMany([ <doc-obj>, <doc-obj>, <doc-obj> ])
- To insert:
db.collectionName.insert(<doc-obj>)
ORdb.collectionName.insert([ <doc-obj>, <doc-obj>, <doc-obj> ])