- Tutorials >
- Collections
Collections¶
On this page
MongoDB stores documents in collections. If a collection does not exist, MongoDB creates the collection when you first insert a document in that collection.
You can also explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.
Capped Collection¶
Capped collections have maximum size or document counts that prevent them from growing beyond maximum thresholds. All capped collections must specify a maximum size and may also specify a maximum document count. MongoDB removes older documents if a collection reaches the maximum size limit before it reaches the maximum document count.
To create a capped collection, use
the capped: true
option along with a size
in bytes.
Convert an Existing Collection to Capped¶
To convert an existing collection from non-capped to capped, use
the convertToCapped
command.
Document Validation¶
If you’re using MongoDB version 3.2 or later, you can use
document validation.
Collections with validations compare each inserted or updated
document against the criteria specified in the validator option.
Depending on the validationLevel
and validationAction
, MongoDB
either returns a warning, or refuses to insert or update the document
if it fails to meet the specified criteria.
The following example creates a contacts
collection with a validator
that specifies that inserted or updated documents should match at
least one of three following conditions:
- the
phone
field is a string - the
email
field matches the regular expression - the
status
field is eitherUnknown
orIncomplete
.
Add Validation to an Existing Collection¶
To add document validation criteria to an existing collection, use the
collMod
command. The example below demonstrates how to add a
validation to the contacts
collection, ensuring that all new
documents must contain an age
field which is a number.
Change Streams¶
As of version 3.6 of the MongoDB server, a new `$changeStream
pipeline stage is supported in the aggregation framework.
Specifying this stage first in an aggregation pipeline allows users to request that notifications are sent for all
changes to a particular collection. The helper method available for change streams on a collection object is preferred
to running a raw aggregation with a $changeStream stage, for the purpose of supporting resumability.
The change stream will attempt to resume one time upon a network error or a server error indicating that a failover is taking place.
To start receiving change notifications, use the method #watch
on a collection:
Each document can be retrieved and processed by your application as in the following code example:
The change documents will expose a resume token at the key ‘_id’. This token can be used to specify a logical starting point for a new a ChangeStream:
A subset of aggregation pipeline stages are available to a change stream and can be passed into the #watch
method: