Basic Commands
Introduction to basic MongoDB commands
Understanding and using basic MongoDB commands is essential for interacting with the database. Below are some of the most common commands used in MongoDB.
Connecting to MongoDB
To start using MongoDB, first connect to the MongoDB server using the mongo shell.
Command
mongo
Creating a Database
Use the following command to create a new database or switch to an existing one:
Command
use myDatabase
Creating a Collection
To create a new collection within the database, use the following command:
Command
db.createCollection("myCollection")
Inserting a Document
To insert a new document into a collection, use the following command:
Command
db.myCollection.insertOne({ name: "John Doe", age: 30 })
Querying Documents
To query documents in a collection, use the following command:
Command
db.myCollection.find({ name: "John Doe" })
Updating a Document
To update an existing document in a collection, use the following command:
Command
db.myCollection.updateOne( { name: "John Doe" }, { $set: { age: 31 } } )
Deleting a Document
To delete a document from a collection, use the following command:
Command
db.myCollection.deleteOne({ name: "John Doe" })