【问题标题】:update a specific object inside an array of object in mongodb [duplicate]更新mongodb中对象数组中的特定对象[重复]
【发布时间】:2018-08-23 01:39:08
【问题描述】:

我有以下文件:

{
   _id: objectId("5aa7abb3c7dc133b0007e6e"),
   name: "first course",
   targets: Array
     0: Object
        id: "11111_rrrr",
        value: "test"
     1: Object
        id: "22222_rrrr",
        value: "hi"
}

所以,我想更改数组[i] 的值。 我的解决方案是:

$update = array(
        'targets.$[].value' => "New Value"
    );

    $result = Course::where("_id", $course_id)->update($update);

它改变了数组的所有值,我该如何解决我的问题??

【问题讨论】:

  • 使用$update = array( 'targets.0.value' => "New Value" );
  • 我有仪表板,所以我不知道数组中的任何索引。我需要一种动态的方式来迭代数组。
  • 你说所以,我要做的就是改变数组[0]的值
  • 对不起,我会改变我的问题。
  • 别抱歉。没关系。那么如何识别数组。是 id 吗?

标签: mongodb laravel


【解决方案1】:

试试这个

db.getCollection('TEST').update({"targets.id" : $course_id},{$set:{"targets.$.value" : "New Value"}})

【讨论】:

    猜你喜欢
    • 2019-04-18
    • 2020-12-18
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    相关资源
    最近更新 更多