我将具有以下结构的文件“ world.json”导入到“世界” MongoDB数据库内的“ mondes”集合中
{
"_id": ObjectId("5dff5a2d98dfef12b0c590b7"),
"Code": "BFA",
"Name": "Burkina Faso",
"Continent": "Africa",
"Region": "Western Africa",
"SurfaceArea": 274000,
"IndepYear": 1960,
"Population": 11937000,
"LifeExpectancy": 46.7,
"GNP": 2425,
"GNPOld": 2201,
"LocalName": "Burkina Faso",
"GovernmentForm": "Republic",
"HeadOfState": "Blaise Compaor�",
"Capital": {
"ID": 549,
"Name": "Ouagadougou",
"District": "Kadiogo",
"Population": 833000
},
"Code2": "BF",
"Cities": [
{
"ID": 550,
"Name": "Bobo-Dioulasso",
"District": "Houet",
"Population": 300000
},
{
"ID": 551,
"Name": "Koudougou",
"District": "Boulkiemd�",
"Population": 105000
}
],
"NotOffLang": [
{
"Language": "Busansi",
"Percentage": 3.5
},
{
"Language": "Dagara",
"Percentage": 3.1
},
{
"Language": "Dyula",
"Percentage": 2.6
},
{
"Language": "Ful",
"Percentage": 9.7
},
{
"Language": "Gurma",
"Percentage": 5.7
},
{
"Language": "Mossi",
"Percentage": 50.2
}
]
}
我写了以下脚本“ update.js”,存储在c:\ $ Mongo \ bin
db.mondes.find({ "Continent": "Africa" }).forEach(
function (doc) {
temp = doc.Capital.Population;
if (doc.Capital.Population > 500000) {
var temp = temp + 1000;
}
else if (doc.Capital.Population < 500000) {
temp = temp + 500;
}
doc.Capital.Population = temp;
db.mondes.save(doc);
}
);
当我尝试在mongo的shell中加载(“ update.js”)时,它给了我这个错误:
2019-12-22T23:02:46.724+0100 E QUERY [js] uncaught exception: TypeError: doc.Capital is undefined :
@update.js:7:1
DBQuery.prototype.forEach@src/mongo/shell/query.js:494:9
@update.js:3:1
@(shell):1:1
2019-12-22T23:02:46.724+0100 E QUERY [js] Error: error loading js file: update.js :
@(shell):1:1
即使我用小写字母而不是“ Captial”写大写字母,上述错误仍然存在。
答案 0 :(得分:0)
最后,我使用((doc || {})。Capital || {})。Population代替了 doc.Capital.Population