- Introduction to MongoDB >
- Databases and Collections
Databases and Collections¶
On this page
MongoDB stores BSON documents, i.e. data records, in collections; the collections in databases.
Databases¶
In MongoDB, databases hold collections of documents.
To select a database to use, in the mongo
shell, issue the
use <db>
statement, as in the following example:
Create a Database¶
If a database does not exist, MongoDB creates the database when you
first store data for that database. As such, you can switch to a
non-existent database and perform the following operation in the
mongo
shell:
The insert()
operation creates both the database
myNewDB
and the collection myNewCollection1
if they do not
already exist.
For a list of restrictions on database names, see Naming Restrictions.
Collections¶
MongoDB stores documents in collections. Collections are analogous to tables in relational databases.
Create a Collection¶
If a collection does not exist, MongoDB creates the collection when you first store data for that collection.
Both the insert()
and the
createIndex()
operations create their respective
collection if they do not already exist.
For a list of restrictions on database names, see Naming Restrictions.
Explicit Creation¶
MongoDB provides the db.createCollection()
method to
explicitly create a collection with various options, such as setting
the maximum size. If you are not
specifying these options, you do not need to explicitly create the
collection since MongoDB creates new collections when you first store
data for the collections.
To modify these collection options, see collMod
.
Modifying Document Structure¶
To change the structure of the documents in a collection, such as add new fields, remove existing fields, or change the field values to a new type, update the documents to the new structure.