Show List

Creating and managing databases and collections

In MongoDB, a database is a container for collections, and a collection is a group of MongoDB documents. To create and manage MongoDB databases and collections, you can use the following commands:

  • Creating a database: To create a new database, you can use the use command followed by the name of the database. For example, to create a database named "mydatabase", you can use the following command:
perl
Copy code
use mydatabase

This command will create a new database if it doesn't exist already.

  • Creating a collection: To create a new collection, you can use the db.createCollection() method followed by the name of the collection. For example, to create a collection named "customers", you can use the following command:
python
Copy code
db.createCollection("customers")

This command will create a new collection in the current database.

  • Inserting documents: To insert a new document into a collection, you can use the db.collection.insertOne() method. For example, to insert a new document into the "customers" collection, you can use the following command:
php
Copy code
db.customers.insertOne({ name: "John Doe", age: 30, email: "john@example.com" })

This command will insert a new document with the given fields into the "customers" collection.

  • Retrieving documents: To retrieve documents from a collection, you can use the db.collection.find() method. For example, to retrieve all documents from the "customers" collection, you can use the following command:
lua
Copy code
db.customers.find()

This command will return all documents in the "customers" collection.

  • Updating documents: To update a document in a collection, you can use the db.collection.updateOne() or db.collection.updateMany() method. For example, to update the email field of a document in the "customers" collection, you can use the following command:
css
Copy code
db.customers.updateOne({ name: "John Doe" }, { $set: { email: "johndoe@example.com" } })

This command will update the email field of the document with the name "John Doe" in the "customers" collection.

  • Deleting documents: To delete a document from a collection, you can use the db.collection.deleteOne() or db.collection.deleteMany() method. For example, to delete a document from the "customers" collection, you can use the following command:
css
Copy code
db.customers.deleteOne({ name: "John Doe" })

This command will delete the document with the name "John Doe" from the "customers" collection.

These are some of the basic commands for creating and managing MongoDB databases and collections.


    Leave a Comment


  • captcha text