Control over the document data

I note that one can put just about anything they want into a document. So I can put temperature in as a string or as an integer. When I go to read as a string, I will only get string results, when I go to read as integer, I will only get integer results ({“temp”:“45”} vs {“temp”:45}). Is there some way to control the contents of a document so that there are not inadvertent mistakes by “contributors”?

It’s somewhat covered in the following courses:

  • M201: MongoDB Performance
  • M320: Data Modelling

You could implement schema validation to prevent this from happening.

Thx. My education continues.

Hi @Jack_65930,

In addition to @007_jb,

You can definitely not only enforce the desired validation rules on your collection but you can also do a whole lot of things using the validationLevel and validationAction options.

In general, this is what it looks like. Here we are setting some validation rules on the contacts collection.

db.createCollection( "contacts",
   { validator: { $or:
         { phone: { $type: "string" } },
         { email: { $regex: /@mongodb\.com$/ } },
         { status: { $in: [ "Unknown", "Incomplete" ] } }
} )

For more information, please refer our documentation on Document Validation.

Hope it helps.

If you have any other issue, please feel free to get back to us.

Happy Learning :slight_smile:

Shubham Ranjan
Curriculum Support Engineer