所以我需要從集合中刪除最低的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