【问题标题】:MongoDB How to update the first item that matches a condition in an array of documents?MongoDB 如何更新与文档数组中的条件匹配的第一项?
【发布时间】:2018-12-24 09:01:32
【问题描述】:

我有一个示例文档:

{
    _id: 1,
    exams: [
               {name: 'a', score: 2},
               {name: 'b', score: 9},
               {name: 'c', score: 7}
           ]
}

对于_id指定的文档,我需要将exams数组中score大于7的第一个元素的score设置为10。

所以对于示例文档,我需要将其更新为:

{
    _id: 1,
    exams: [
               {name: 'a', score: 2},
               {name: 'b', score: 10},
               {name: 'c', score: 7}
           ]
}

这个任务的 Mongo shell 查询是什么?

【问题讨论】:

    标签: arrays mongodb mongo-shell


    【解决方案1】:

    使用 $gt 找到更高的分数

    updateOne({"exams.score":{ $gt: 7 }},{$set:{"exams.$.score":"10"})
    

    【讨论】:

      猜你喜欢
      • 2011-12-19
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 2019-09-03
      • 2017-02-20
      相关资源
      最近更新 更多