【问题标题】:Use of $ operate in mongodb php querymongodb php查询中$操作的使用
【发布时间】:2014-10-31 23:59:18
【问题描述】:

来自 http://docs.mongodb.org/manual/reference/operator/update/positional/ 的 MongoDB 文档 可以使用$ 运算符来更新内部字段,例如给定的示例

{“_id”:4,“等级”:[{等级:80,平均值:75,标准:8}, {等级:85,平均:90,标准:5}, {等级:90,平均:85,标准:3}]}

使用位置$运算符更新嵌入文档中std字段的值,等级为85:

db.students.update( { _id: 4, "grades.grade": 85 }, { $set: { "grades.$.std" : 6 } } )

有人可以解释一下$ 是如何发挥作用的吗?为什么 MongoDB 开发人员没有让它变得更简单,比如我们可以使用 "grades.grade":85 查找文档并使用 "grades.std":6 进行更新?还是我遗漏了什么?

【问题讨论】:

    标签: php mongodb


    【解决方案1】:

    位置$ 运算符充当与查询文档匹配的第一个元素的占位符。 如果没有$,您将不得不执行额外的步骤来获取匹配元素的索引。否则索引将被硬编码。

    更新示例:

    db.students.update( { _id: 4, "grades.grade": 85 }, { $set: { "grades.$.std" : 6 })
    

    "grades.grade":85find a document where 'grades' has 'grade' set to `85

    "grades.2.std":6 读作within 'grades', set 'std' to 6 for the element at index 2

    "grades.$.std:6" 读作within 'grades', set 'std' to 6 for the first matched element

    "grades.std":6 听起来像within 'grades', for all elements set 'std' to '6'。在 MongoDB 2.6 中,这不是 supported feature

    【讨论】:

      猜你喜欢
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-22
      • 2014-12-01
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      • 2018-07-13
      相关资源
      最近更新 更多