这个问题已经很久没有被问到了。
无论如何,如果有人经历过这个。
For MongoDB 3.6和更高版本,这可以使用验证器来实现。
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name","surname","books"],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
surname: {
bsonType: "string",
description: "must be a string and is required"
},
books: {
bsonType: [ "array" ],
items: {
bsonType: "object",
required:["name","no"],
properties:{
name:{
bsonType: "string",
description: "must be a string and is required"
},
no:{
bsonType: "number",
description: "must be a number and is required"
}
}
},
description: "must be a array of objects containing name and no"
}
}
}
}
})
这一款可以满足您的所有要求。
欲了解更多信息,请参阅此link