我在MongoDB中有以下方案:
{
"_id" : 100,
"name" : "John Doe",
"scores" : [
{
"type" : "exam",
"score" : 334.45023
},
{
"type" : "quiz",
"score" : 11.78273309957772
},
{
"type" : "homework",
"score" : 6.676176060654615
},
{
"type" : "homework",
"score" : 35.8740349954354
}
]
}
我正在寻找一种方法来删除分数最少的作业。我找到了一个相关的答案here但是,它没有多大帮助,因为我只需要找出得分最低的“作业”并将其删除。
我正在使用MongoDB和PyMongo驱动程序。
答案 0 :(得分:3)
您需要添加match
,如:
myresults = scores.aggregate( [ { "$unwind": "$scores" }, { '$match': {'scores.type': "homework" } }, { "$group": { '_id':'$_id' , 'minitem': { '$min': "$scores.score" } } } ] )
for result in myresults['result']:
scores.update( { '_id': result['_id'] }, { '$pull': { 'scores': { 'score': result['minitem'] } } } )
答案 1 :(得分:1)
我尝试使用本机mongodb命令,但它确实有效。 使用以下2个命令使其工作。
1) cursor = db.students.aggregate([{“$ unwind”:“$ scores”},{“$ match”:{“scores.type”:“homework”}},{“$ group”:{'_ id' :'$ _id','minitem':{'$ min':“$ scores.score”}}}]),null
2) cursor.forEach(function(coll){db.students.update({'_ id':coll._id},{'$ pull':{'scores':{'score':coll.minitem}}})})
答案 2 :(得分:1)
以下是使用Python的解决方案:
students = db.students
cursor = students.find({})
for doc in cursor:
hw_scores = []
for item in doc["scores"]:
if item["type"] == "homework":
hw_scores.append(item["score"])
hw_scores.sort()
hw_min = hw_scores[0]
students.update({"_id": doc["_id"]},
{"$pull":{"scores":{"score":hw_min}}})
答案 3 :(得分:0)
我认为使用本机mongodb命令是不可能的。我认为最好的方法是编写一个javascript函数来降低最低分并在服务器上运行它;这将具有自动化的优势,因此当您从中移除列表时,无法更新列表,从而保持一致。
以下是一些文档:http://docs.mongodb.org/manual/applications/server-side-javascript/
答案 4 :(得分:0)
我在这里听了第三个答案。 Removing the minimum element of a particular attribute type in MongoDB
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/school', function(err, db) {
if(err) throw err;
var students = db.collection('students');
cursor = students.aggregate(
[{ "$unwind": "$scores" },
{ "$match": { "scores.type": "homework"}},
{ "$group": {'_id': '$_id', 'minitem': {
'$min': "$scores.score"
}
}
}
]);
cursor.forEach(
function(coll) {
students.update({
'_id': coll._id
}, {
'$pull': {
'scores': {
'score': coll.minitem
}
}
})
});
});