This article is a cheat sheet for MongoDB commands. You will find a list of the most essential and handy commands that you will frequently use here.
Contents
hide
Introduction
As a developer, you will need to frequent reference to MongoDB commands. Most importantly, you will frequently have to perform CRUD and filter operations. This cheat sheet will help you for that purpose and more.
Task | Command |
View database currently in use | db |
Create a new database | use <DB_NAME> |
Connect to a database (Same command as before) | use <DB_NAME> |
Create a new collection | db.createCollection(‘MY_COLLECTION’) |
Insert a record in a collection | db.<My_Collection>.insertOne({MY_JSON_DATA} |
Insert multiple records | db.<My_Collection>.insertMany([{MY_JSON_DATA_ARRAY]} |
List all items in a collection | db.<My_Collection>.find() |
Filtering a collection | db.<My_Collection>.find({ FILTER_CRITERIA }) Eg: db.Books.find({“author”:”me”}) |
Removing items from a collection | db.<My_Collection>.remove( { FILTER_CRITERIA} ) Eg: db.Books.remove({“author”:”me”} |
Updating a document | db. <My_Collection>.updateOne( { FILTER_CRITERIA} , { $set: {<OLD_VALUE> : <NEW_VALUE>}} Eg: db.Books.updateOne({id:3, “author” : “me”}, { $set: {“author”:”her”}}) |