Databases and Collections

MongoDB stores BSON documents, i.e. datarecords, in collections; the collections indatabases.

A collection of MongoDB documents.

Databases

In MongoDB, databases hold collections of documents.

To select a database to use, in the mongo shell, issue theuse <db> statement, as in the following example:

  1. use myDB

Create a Database

If a database does not exist, MongoDB creates the database when youfirst store data for that database. As such, you can switch to anon-existent database and perform the following operation in themongo shell:

  1. use myNewDB
  2.  
  3. db.myNewCollection1.insertOne( { x: 1 } )

The insertOne() operation creates both thedatabase myNewDB and the collection myNewCollection1 if they donot already exist. Be sure that both the database and collection namesfollow MongoDB Naming Restrictions.

Collections

MongoDB stores documents in collections. Collections are analogous totables in relational databases.

Create a Collection

If a collection does not exist, MongoDB creates the collection when youfirst store data for that collection.

  1. db.myNewCollection2.insertOne( { x: 1 } )
  2. db.myNewCollection3.createIndex( { y: 1 } )

Both the insertOne() and thecreateIndex() operations create theirrespective collection if they do not already exist. Be sure that thecollection name follows MongoDB Naming Restrictions.

Explicit Creation

MongoDB provides the db.createCollection() method toexplicitly create a collection with various options, such as settingthe maximum size or the documentation validation rules. If you are notspecifying these options, you do not need to explicitly create thecollection since MongoDB creates new collections when you first storedata for the collections.

To modify these collection options, see collMod.

Document Validation

New in version 3.2.

By default, a collection does not require its documents to have thesame schema; i.e. the documents in a single collection do not need tohave the same set of fields and the data type for a field can differacross documents within a collection.

Starting in MongoDB 3.2, however, you can enforce documentvalidation rules for a collection duringupdate and insert operations. See Schema Validation fordetails.

Modifying Document Structure

To change the structure of the documents in a collection, such as addnew fields, remove existing fields, or change the field values to a newtype, update the documents to the new structure.

Unique Identifiers

New in version 3.6.

Note

The featureCompatibilityVersion must be set to "3.6" or greater. Formore information, see View FeatureCompatibilityVersion.

Collections are assigned an immutable UUID. Thecollection UUID remains the same across all members of a replica setand shards in a sharded cluster.

To retrieve the UUID for a collection, run either thelistCollections commandor the db.getCollectionInfos() method.