Databases and Collections
MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents, though it contains more data types than JSON. For the BSON spec, see bsonspec.org. See also BSON Types.
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:
use myDB
switched to db myDB
Create a Database
If a database does not exist, MongoDB creates the database when you first store data for that database.
use myNewDB
switched to db myNewDB
db.myNewCollection1.insertOne( { x: 1 } )
{
"acknowledged" : true,
"insertedId" : ObjectId("5b56bf751fc0b7f2e167d169")
}
The insertOne() operation creates both the database myNewDB and the collection myNewCollection1 if they do not already exist.
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.
db.myNewCollection2.insertOne( { x: 1 } )
{
"acknowledged" : true,
"insertedId" : ObjectId("5b56bfb71fc0b7f2e167d16a")
}
db.myNewCollection3.createIndex( { y: 1 } )
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
Both the insertOne() and the createIndex() operations create their respective collection if they do not already exist.
Explicit Creation
MongoDB provides the db.createCollection() method to explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.
Document Validation
By default, a collection does not require its documents to have the same schema. Starting in MongoDB 3.2, however, you can enforce document validation rules for a collection during update and insert operations. See Schema Validation for details.
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.
Unique Identifiers
Collections are assigned an immutable UUID. The collection UUID remains the same across all members of a replica set and shards in a sharded cluster.
To retrieve the UUID for a collection, run either the listCollections command or the db.getCollectionInfos() method.