snippetMinor
How do I explicitly define data types for a MongoDB collection?
Viewed 0 times
howmongodbcollectionexplicitlydefinefortypesdata
Problem
How do I explicitly define data types for a MongoDB collection?
I understand that in Mongo if a collection doesn't exist it will create it when you insert the document, but I know the fields and data types of the collection before hand and I want to create it.
I have created an example collection using:
According to this document from the MongoDB documentation, there are various data types in MongoDB, but again,
How do I explicitly define data types for a MongoDB collection?
I understand that in Mongo if a collection doesn't exist it will create it when you insert the document, but I know the fields and data types of the collection before hand and I want to create it.
I have created an example collection using:
db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )According to this document from the MongoDB documentation, there are various data types in MongoDB, but again,
How do I explicitly define data types for a MongoDB collection?
Solution
Use the mongoDB document validator. It was introduced in version 3.2 and allow you to validate documents during updates and insertions. It need to be defined when the collection is being created.
You can define the data types for a collection like this:
Document validator support types:
https://docs.mongodb.com/manual/reference/operator/query/type/
Official info about document validator:
https://docs.mongodb.com/manual/core/document-validation/
You can define the data types for a collection like this:
db.createCollection( "log",
{ validator: { $and:
[
{ capped: { $type: "bool" } },
{ size: { $type: "int" } },
{ max: { $type: "int" } }
]
}
} )Document validator support types:
https://docs.mongodb.com/manual/reference/operator/query/type/
Official info about document validator:
https://docs.mongodb.com/manual/core/document-validation/
Code Snippets
db.createCollection( "log",
{ validator: { $and:
[
{ capped: { $type: "bool" } },
{ size: { $type: "int" } },
{ max: { $type: "int" } }
]
}
} )Context
StackExchange Database Administrators Q#73164, answer score: 3
Revisions (0)
No revisions yet.