Using MongoDB on Linux After Install
After installing MongoDB, you can use it by following these steps:
- Start the MongoDB server by running the command “sudo service mongodb start” or “sudo systemctl start mongodb” in the terminal.
- Run MongoDB Shell: Enter the MongoDB Shell by running the command “mongo” in the terminal.
- Create or select a database: In the MongoDB Shell, use the “use” command to create or select a database. For example, run “use mydb” to create a database named “mydb” (if it doesn’t exist) or select the existing “mydb” database.
- Performing database operations: In the MongoDB Shell, you can execute a range of database operations such as inserting documents, querying documents, updating documents, and deleting documents. Here are some common operation examples:
- Inserting documents: To add one or multiple documents, use the insertOne() or insertMany() methods. For example, running db.collection.insertOne({name: “John”}) will insert a document into the collection named “collection”.
- Search documents: Use the find() method to query documents. For example, run db.collection.find({}) to search for all documents in the “collection” collection.
- Update documents: Use the updateOne() or updateMany() methods to update one or multiple documents. For example, running db.collection.updateOne({name: “John”}, {$set: {age: 30}}) updates the age field of the document named “John” in the “collection” collection to 30.
- Delete documents: Use the deleteOne() or deleteMany() methods to remove one or multiple documents. For example, running db.collection.deleteOne({name: “John”}) will delete the document named “John” in the “collection” collection.
- To exit the MongoDB Shell, simply run the command quit() within the MongoDB Shell.
Please note that the above examples are just basic usage scenarios, MongoDB has more features and operations to explore and learn. You can refer to the MongoDB official documentation for more details and advanced usage.