所以我需要从集合中删除最低的hw分数。我在没有错误的情况下在mongoShell中运行它。但是写入结果只能匹配但不能修改。有人可以告诉我为什么吗?更新方法无误地运行,但结果没有更新
这里是数据库:
db.students.find({ _id : 137 }).pretty()
{
"_id" : 137,
"name" : "Tamika Schildgen",
"scores" : [
{
"type" : "exam",
"score" : 4.433956226109692
},
{
"type" : "quiz",
"score" : 65.50313785402548
},
{
"type" : "homework",
"score" : 89.5950384993947
}
]
}
下面是我的解决办法:
// sort by lowest score; writeresults are modified.
db.students.update(
{"scores.type":"homework"},
{$push: {"scores": { $each: [], $sort: { score: 1} }}},
{multi: true}
)
// should remove last element of homework; writeresults are not modified, not sure why
db.students.update(
{"scores.type":"homework"},
{$pop: { score: -1 }},
{multi: true}
)
// Alternatively, below query also generated same writeresults
db.students.update(
{},
{$pull: { "scores": {$elemMatch: {"type": "homework"} }}},
{multi: true}
)
你想'scores'在'$ pop',不'score'。 – wdberkeley 2014-10-31 15:58:46
@wdberkeley谢谢!这很有道理,删除数组中的元素而不是文档。 '$ pull'怎么样,为什么它不起作用? – 2014-11-02 16:40:28