MongoDB is a document-oriented NoSQL database platform that provides high performance, high availability and easy scalability. It works based on the concept of collections and documents, rather than tables and rows, as in relational databases.
6. Working with databases in MongoDB
Working with databases in MongoDB involves several operations such as creating, reading, updating, and deleting data. Let's discuss each of these operations in detail.
Database Creation
In MongoDB, creating a database is as simple as issuing a command. The 'use' command followed by the database name is used to create a new database. If the mentioned database already exists, MongoDB will simply select it for use. If it doesn't exist, it will be created.
use myDatabase
This command creates a new database called 'myDatabase'. Note that MongoDB is case-sensitive, therefore 'myDatabase' and 'mydatabase' would be considered different databases.
Data Reading
Reading data in MongoDB is done using the 'find' command. This command returns all documents within a collection. For example, to read all documents in the 'myCollection' collection, you would use the following command:
db.myCollection.find()
This command returns all documents in the 'myCollection' collection. You can also add search criteria to the 'find' command to filter the results.
Data Update
Updating data in MongoDB is done using the 'update' command. This command updates the values of existing documents. For example, to update a document in the 'myCollection' collection, you would use the following command:
db.myCollection.update({name: 'John'}, {$set: {age: 30}})
This command updates the age of 'John' to 30 in the collection 'myCollection'. Note that the first argument of the 'update' command is a search criterion to find the document to be updated. The second argument is an update operator that sets the new values for the document's fields.
Data Deletion
Deleting data in MongoDB is done using the 'remove' command. This command deletes documents from a collection. For example, to delete a document from the 'myCollection' collection, you would use the following command:
db.myCollection.remove({name: 'John'})
This command deletes all documents in the collection 'myCollection' where the name is 'John'. Note that the argument of the 'remove' command is a search criterion to find the documents to be deleted.
Conclusion
Working with databases in MongoDB involves a variety of operations, each of which is performed using a specific command. The simplicity and flexibility of these commands make MongoDB a popular choice for managing NoSQL databases.