我是MongoDB的新手。我想创建一个集合并将文档插入到该集合中。
我已经创建了一个数据库,也创建了一个集合,但是当集合中有一个有趣的文档时出现错误。
在我的代码下面
db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name", "year", "major", "gpa", "address.city", "address.street" ],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
gender: {
bsonType: "string",
description: "must be a string and is not required"
},
year: {
bsonType: "int",
minimum: 2017,
maximum: 3017,
exclusiveMaximum: false,
description: "must be an integer in [ 2017, 3017 ] and is required"
},
major: {
enum: [ "Math", "English", "Computer Science", "History", null ],
description: "can only be one of the enum values and is required"
},
gpa: {
bsonType: [ "double" ],
minimum: 0,
description: "must be a double and is required"
},
"address.city" : {
bsonType: "string",
description: "must be a string and is required"
},
"address.street" : {
bsonType: "string",
description: "must be a string and is required"
}
}
}
}
})
在记录中插入记录
db.students.insert({
name: "Pramod Kushwaha",
gender:"Male",
year: NumberInt(2018),
major: "Math",
gpa: NumberDecimal(3.22),
address: {
city: "NYC",
street: "Narol"
}
})
遇到错误
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
答案 0 :(得分:1)
我得到了答案
db.students.insert({
name: "Pramod Kushwaha",
gender:"Male",
year: NumberInt(2018),
major: "Math",
gpa: 3.22,
address: {
city: "NYC",
street: "Narol"
}
})
在上面的插入中,查询在gpa
字段中有数据类型问题。我将NumberDecimal(3.22)
更改为3.22
作为双数据类型值。