最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

[Array内的MongoDB更新项目

网站源码admin25浏览0评论

[Array内的MongoDB更新项目

[Array内的MongoDB更新项目

我想更新数组中数组内的现有项目。

我的文档结构如下:

    {
  "_id":"a1",
  "projects":[{
    "_id": "b1",
    "title":"Title A",
    "task":[
           {"_id": "c1",
            "title":"Title B"},
            {"_id": "c2",
            "title":"Title C"},
            {"_id": "c3",
            "title":"Title D"}
          ],

}]
}

假设我们要更改“任务”:

{"_id": "c2",
 "title":"Title C"}

{"_id": "c2",
 "title":"Title C1"}

有人知道更新此子文档的正确方法吗?

回答如下:通过将$set与posititonal operator和arrayFilters组合使用,这应该是可行的:

db.getCollection('so-test').updateOne( { _id: "a1"}, { $set: { "projects.$[].task.$[task].title": "Title C1" } }, { arrayFilters: [ {"task.title": "Title C"} ]} )

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论