3天前我开始学习MongoDB,在做练习时,服务器出现了一些意外的行为。奇怪的MongoDB行为
的行使要求写一个小程序,从具有以下结构的文档中删除最低功课成绩(这个文件是学生集合内):
{
"_id": 10,
"name": "Demarcus Audette",
"scores": [
{
"type": "exam"
"score": 47.42086
},
{
"type": "quiz"
"score": 44.83456
},{
"type": "homework"
"score": 39.0178956
},{
"type": "homework"
"score": 14.578344
}
]
}
不管怎么说,写程序我意外地犯了一个错误。这是我写的
def removeHW(hw):
# establish a connection to the database
connection = MongoClient("localhost", 27017)
# get a handle to the school database
db = connection.school
students = db.students
# extract the scores into a list
scores = []
for i in range(1, len(hw)):
scores.append(hw[i]["score"])
# Now remove the lowest score from the database
query = {"_id": hw[0], "scores.score": min(scores),"scores.type": "homework"}
try:
students.remove(query)
except:
print "Unexpected error:", sys.exc_info()[0]
程序
我的程序背后的逻辑是,之后我提取含有从学生两个家庭作业和_id词典列表集合,我遍历所有的字典,并把它传递给removeHW()函数。
我犯的错误是,我写道:
query = {"_id": hw[0], "scores.score": min(scores),"scores.type": "homework"}
students.remove(query)
当我写了下面的(这是正确的解决方案):
query = {"_id": hw[0], "scores.type": "homework"}
students.update(query, {"$pull": {"scores": {"score" : min(scores)}}})
是的,我知道到现在为止似乎一切都安然无恙。我遇到的问题是,使用第一个解决方案(错了),当MongoDB中删除了所有来自学生收集的文件,并创建了一个新的集合包含所有从学生子文档得分集合,除了一个我想要的去除(功课最低的作业)。我发现这种行为非常奇怪,因为我没有使用过NoSQL数据库的经验,所以我想知道是什么导致MongoDB做到这一点,为什么。
如果有人能帮助我理解,请做。我会永远感谢你。
“永远感激?” :)这是一个很长的时间。你确定所有的文件都被删除了吗? (“学生”系列中有多少人)?'_id'应该将其限制为一个文档。而且,鉴于您提供的代码中没有插入/更新,我不明白它会如何完成您所说的内容。 – WiredPrairie
是的,我确定,学生收藏中有200个文档,mongo创建的分数集合的结构如下:{{“_id”:10,“name”:“Demarcus Audette”,“type”: “考试”,“分数”:44.654},{“_id”:10,“name”:“Demarcus Audette”,“type”:“家庭作业”,score:45.456},...},我告诉你这是我见过的最奇怪的事 – Codejunky
你通过移除HW的结构是什么? – innoSPG