验证 MongoDB 中数组项的类型

Validating type of array items in MongoDB

我正在使用 MongoDB 4.0.

我的 collection 中的文档可以有一个包含整数数组的 numbers 字段。我们可以使用下面的代码验证 numbers 确实是一个数组,但是是否可以确保它们是整数?

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

我看过 validation docs and the BSON type docs 但其中任何一个都没有说明任何内容。一个示例显示了一个包含在方括号 (["double"]) 中的字段,但该类型并未被描述为数组,添加方括号似乎没有任何效果。

似乎还有另一个属性,items,您可以在其中定义数组中项目的方案

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

这个属性好像be from mongo 3.6

您需要在“array”之后添加一个“,”字符,如下所示:

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