【问题标题】:update of a subdocument's field in an array of documents in MongoDB using the positional operator with Mango使用 Mango 的位置运算符更新 MongoDB 中文档数组中子文档的字段
【发布时间】:2015-07-31 11:17:42
【问题描述】:

我有一堆文档,每个文档都包含一个类似于以下的数组:

{
  _id: 4,
  grades: [
     { grade: 80, mean: 75, std: 8 },
     { grade: 85, mean: 90, std: 5 },
     { grade: 90, mean: 85, std: 3 }
  ]
}

并且我希望更新具有相应grade=85 的子文档的std 字段。 我正在使用Mango driver,如果我尝试在如下语句中使用positional ($) operator,它的update 方法会抱怨或默默忽略更新:

my $result = $self->collection->update({_id => 4, grades => {grade => 85}}, {'$set' => {'grades.$.std' => 6, 'grades.$.new_field' => 'test'}});

my $result = $self->collection->update($oid, {grades => {grade => 85}}, {'$set' => {'grades.$.std' => 6}});

并且无法正确更新子文档。 Mango update 方法在未指定位置运算符时有效。另外,find_and_modify 并没有给我带来更好的结果。

当尝试使用 $elemMatch 运算符时(虽然我认为不需要,因为我只有一个查询)我得到了一些类似于 Write error at index 0: The dollar ($) prefixed field '$elemMatch' in 'grades.$elemMatch' is not valid for storage. at ... 的东西

请问我该如何处理 Mango?

如果 Mango 的 update 方法不支持这个,MongoDB official Perl driver 是否支持?

【问题讨论】:

    标签: mongodb perl


    【解决方案1】:

    MongoDB official Perl driver 支持在使用positional ($) operator 的同时进行更新。

    以下将更新嵌入在特定文档中的数组的子文档中的字段:

    my $oid = MongoDB::OID->new("...");
    $self->collection->update(
      {_id => $oid, 'grades.grade' => 85},
      {'$set' => {'grade.$.new_field' => 'test'}}
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-20
      • 2017-04-09
      • 2016-11-23
      • 2016-12-31
      • 2016-11-04
      • 2019-08-21
      • 1970-01-01
      • 2012-11-26
      相关资源
      最近更新 更多