mongodb更新和推送对象数组

utugiqy6  于 2023-02-15  发布在  Go
关注(0)|答案(2)|浏览(144)

我有一个简单的学生集合:

{
    "_id": "btv7865reVGlksabv",
    "students": [
        {
            "name": "John",
            "age": 30
        },
        {
            "name": "Henry",
            "age": 25
        }
    ]
}

现在我想把新学员推到这个数组中:

const newStudents = [
    {
        "name": "Mike",
        "age": 22
    },
    {
        "name": "Kim",
        "age": 20
    }
]

目前为止我尝试的是:

Students.update(
    {
        "_id": "btv7865reVGlksabv"
    },
    {
        $push: {
            "students": newStudents
        }
    }
);

由于某种原因,上述查询无法更新我的收藏。有人能帮助我更正此查询吗?

qvsjd97n

qvsjd97n1#

$push$each连接起来

db.collection.update({
  "_id": "btv7865reVGlksabv"
},
{
  $push: {
    "students": {
      $each: [
        {
          "name": "Mike",
          "age": 22
        },
        {
          "name": "Kim",
          "age": 20
        }
      ]
    }
  }
})

Mongo Playground

368yc8dk

368yc8dk2#

也许是这样的:

db.collection.update({},
[
 {
  $addFields: {
  students: {
    $concatArrays: [
      "$students",
      [
        {
          name: "New1",
          age: "New1"
        },
        {
          name: "New2",
          age: "New2"
        }
      ]
    ]
  }
}
}
])

解释:
使用$addFileds-〉$concatArrays通过聚合管道(4.2+)更新,将新数组中的元素添加到现有数组中...
Playground

相关问题