MongoDB is a popular NoSQL document-oriented database used for handling large volumes of data. In this tutorial, we will cover the basics of MongoDB and how to interact with it using the MongoDB shell.
- Installation and Setup:
To get started with MongoDB, you need to install it on your system. You can download the appropriate version of MongoDB for your operating system from the official website (https://www.mongodb.com/try/download/community). After downloading and installing MongoDB, you should start the MongoDB server by running the following command:
mongod
To connect to MongoDB, open a new terminal window and run the following command:
To create a new database, use the
A collection is a group of related documents stored in MongoDB. To create a new collection, you can use the
To insert a new document into a collection, use the
To retrieve documents from a collection, use the
To update a document in a collection, use the
To remove a document from a collection, use the
To drop a collection, use the
To drop a database, use the
- Connecting to MongoDB:
To connect to MongoDB, open a new terminal window and run the following command:mongo
This will open the MongoDB shell.
- Creating a Database:
To create a new database, use the use
command followed by the name of the database you want to create:use mydatabase
If the database doesn't exist, it will be created automatically.
- Creating a Collection:
A collection is a group of related documents stored in MongoDB. To create a new collection, you can use the db.createCollection()
method:db.createCollection("mycollection")
- Inserting Documents:
To insert a new document into a collection, use the db.collection.insert()
method:db.mycollection.insert({name: "John", age: 30})
- Querying Documents:
To retrieve documents from a collection, use the db.collection.find()
method:db.mycollection.find()
This will return all documents in the collection. You can also specify a query criteria:
db.mycollection.find({name: "John"})
This will return all documents where the name is "John".
- Updating Documents:
To update a document in a collection, use the db.collection.update()
method:db.mycollection.update({name: "John"}, {$set: {age: 35}})
This will update the age of the document where the name is "John".
- Removing Documents:
To remove a document from a collection, use the db.collection.remove()
method:db.mycollection.remove({name: "John"})
This will remove all documents where the name is "John".
- Dropping a Collection:
To drop a collection, use the db.collection.drop()
method:db.mycollection.drop()
This will drop the "mycollection" collection.
- Dropping a Database:
To drop a database, use the db.dropDatabase()
method:db.dropDatabase()
This will drop the "mydatabase" database.
These are the basic operations you can perform with MongoDB. For more advanced usage, you can explore the official MongoDB documentation.
Comments
Post a Comment