Search code examples
mongodbvalidationbson

Validating type of array items in MongoDB


I am using MongoDB 4.0.

Documents in my collection can have a numbers field that holds an array of integers. We can validate that numbers is indeed an array by using the below code, but is it possible to make sure that they are integers?

properties: {
  numbers: {
    bsonType: 'array'
  }
 }

I have looked at the validation docs and the BSON type docs but nothing in either of those says anything about it. One example shows a field enclosed in square brackets (["double"]) but the type is not described as being an array and adding the brackets seems to have no effect.


Solution

  • There seems to be another attribute, items, where you define the scheme for the items in the array

    properties: {
      numbers: {
        bsonType: 'array',
        items: {
          bsonType: 'int'
        }
      }
    }
    

    This attribute seems to be from mongo 3.6