所以我需要从收集中删除最低的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}
)
答案 0 :(得分:0)
根据mongodb文档,您应该如何更新嵌入式文档。
使用多个字段匹配更新嵌入式文档
$
运算符可以更新与$elemMatch()
运算符指定的多个查询条件匹配的第一个数组元素。
考虑students
集合中的以下文档,其grades
字段值是嵌入文档的数组:
{
_id: 4,
grades: [
{ grade: 80, mean: 75, std: 8 },
{ grade: 85, mean: 90, std: 5 },
{ grade: 90, mean: 85, std: 3 }
]
}
在下面的示例中,$
运算符更新了第一个嵌入文档中std
字段的值,grade
字段的值为less than or equal to 90 and a mean field with a value greater than 80
:
db.students.update(
{
_id: 4,
grades: { $elemMatch: { grade: { $lte: 90 }, mean: { $gt: 80 } } }
},
{ $set: { "grades.$.std" : 6 } }
)
此操作更新与条件匹配的第一个嵌入文档,即数组中的第二个嵌入文档:
{
_id: 4,
grades: [
{ grade: 80, mean: 75, std: 8 },
{ grade: 85, mean: 90, std: 6 },
{ grade: 90, mean: 85, std: 3 }
]
}