Here are some common MongoDB commands for working with a database:
1. Creating a Database: To create a new database in MongoDB, you can use the `use` command. For example, to create a database called "mydb", you can run:
use mydb
2. Inserting Documents: To insert documents (records) into a collection (similar to a table in relational databases), you can use the `insertOne` or `insertMany` commands. Here's an example of inserting a document into a collection called "users":
db.users.insertOne({ name: "John", age: 30, email: "john@example.com" })
3. Querying Documents: To retrieve documents from a collection, you can use the `find` command. Here's an example of querying all documents from the "users" collection:
db.users.find()
4. Updating Documents: To update existing documents in a collection, you can use the `updateOne` or `updateMany` commands. For instance, to update the age of a user with the name "John", you can run:
db.users.updateOne({ name: "John" }, { $set: { age: 35 } })
5. Deleting Documents: To delete documents from a collection, you can use the `deleteOne` or `deleteMany` commands. For example, to delete a user with the name "John", you can run:
db.users.deleteOne({ name: "John" })
6. Indexing: To improve the query performance, you can create indexes on specific fields in a collection using the `createIndex` command. Here's an example of creating an index on the "email" field in the "users" collection:
db.users.createIndex({ email: 1 })
7. Aggregation: MongoDB provides powerful aggregation features for performing complex operations on data. You can use the `aggregate` command to perform operations like grouping, filtering, sorting, and calculating aggregations. Here's an example of calculating the average age of users in the "users" collection:
db.users.aggregate([
{ $group: { _id: null, avgAge: { $avg: "$age" } } }
])
These are just a few examples of MongoDB commands for working with databases. MongoDB offers a rich set of commands and features for data manipulation, aggregation, indexing, and more. It's recommended to refer to the MongoDB documentation for a comprehensive list of commands and their usage.