Q1. What is a database in MongoDB?
In MongoDB, a database is a container for collections. Each database gets its own set of files on the file system. A single MongoDB server can host multiple databases. To switch to a database, use
use mydb
in mongosh. If the database doesn't exist, MongoDB creates it when you first store data.Q2. What is a collection in MongoDB?
A collection is a group of MongoDB documents, equivalent to a table in relational databases. Collections are schema-less, meaning documents within a collection can have different fields. Collections are created implicitly when you insert the first document, or explicitly using
db.createCollection("users")
Q3. How do you create and drop a database?
There's no explicit create database command. To create a database, simply switch to it using
use newdb
and insert a document. To drop a database, use db.dropDatabase()
after switching to it.Q4. How do you list all databases and collections?
To list all databases:
show dbs
To list collections in the current database: show collections
Or db.getCollectionNames()
Q5. Can you rename a collection?
Yes, you can rename a collection using the renameCollection() method:
db.users.renameCollection("customers")
This operation is atomic and only works within the same database. It does not copy the collection, it just renames it.